SlideShare a Scribd company logo
Java
Bad coding practices
Gustavo Michael Carrion
Introduction
Aside from what is defined as conventional bad java coding practices such as
variables/methods/package naming, code formatting, among others. There are
some others that I had the chance to experience during my years as a JEE
engineer that I would like to share.
Therefore in the following slides I am going to explain five bad coding practices by
giving a short description of the problem then showing a poorly implemented code
snippet, on the other hand a suggestion on how to fix or prevent this issue will be
given along with a code snippet containing the correct implementation.
Bad coding practices examples
Problem: Presentation layer has high coupling with business
logic layer
One of the principles of good software
design is loose coupling, if the
presentation layer for example the web
application must have the business
layer logic referenced in his classpath
creates high coupling, which creates
dependency making different jars
dependant.
Solution: Create interfaces within a new jar to be
referenced from client applications.
By exposing business logic methods
through interfaces coupling is reduced
this allows seamless modification of
the business logic without having to
tweak the clients, also a good practice
is to put the entities along with these
interfaces so it is possible to pass
them as parameters.
public interface IGoodAppController { //Client jar code
public String calculateGoodness(ScheduledMachine schMach);
}
public class GoodAppController implements IGoodAppController {
@Override //Business jar logic
public String calculateGoodness(ScheduledMachine schMach) {
return "All good!";
}}
//Single jar logic
public class BadAppController {
public String calculateGoodness(ScheduledMachine schMach) {
return "Im highly coupled to you now!";
}
}
Bad coding practices examples (Cont. 2/5)
Problem: Hard coded environment dependant variables
Hard coding variables can lead to
application crashes while moving from
development to test / production
environments for example while looking
for IPs that only exists on a given
environment, furthermore if they are left
in a .java file they will be compiled to an
uneditable .class.
Solution: Make a properties file for constants or store them
in the database.
By putting everything in a single place
to change we can overcome this
problem, by creating a .properties file:
public class Good {
public static final String DB_HOST = "ipaddr";
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
String ipAddr;
try {
input = new FileInputStream("envconst.properties"); // load prop file
prop.load(input); // get the property and print it
ipAddr=prop.getProperty(DB_HOST);
… //continues in the next slide
Another alternative is to create within
the catalog table of the database one
catalog that holds all these variables.
public class Bad {
public static final String DB_HOST = "192.168.1.1";
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
String ipAddr;
try {
ipAddr=DB_HOST; // set the property value
… //continues in the next slide
Bad coding practices examples (Cont. 3/5)
Problem: Catching the Exception superclass
Throwing a very general exception
makes an application recovery almost
impossible and increases debug
complexity by making the source of the
exception hard to trace, this can lead to
frequent application crashes and
extended application downtimes:
Solution: Catch exceptions related to the sentences being
executed in that block of code.
Create a catch block for every kind of
expected subclass exception and in
the last block finally catch the
Exception superclass so it's easier to
identify the problem:
//continues from the previous slide
} catch (FileNotFoundException e){
System.out.println("File not found Exception"); //Short description of
the exception
e.printStackTrace(); //Print the trace to see what is wrong
} catch (IOException ex) {
System.out.println("I/O General Exception"); //A more general exception
is thrown
ex.printStackTrace();
} catch (Exception ex) {
System.out.println("General Exception"); //The base Exception superclass
will catch any other exception
ex.printStackTrace();
}
//continues from the previous slide
} catch (Exception ex) {
System.out.println("General Exception");
ex.printStackTrace();
}
Bad coding practices examples (Cont. 4/5)
Problem: Files cannot be accessed / cannot open any more
database connections.
If there is a file opened / being edited or
a database connection opened, if a
close statement is not issued the
resource will remain open until the
database times it out, preventing access
to that resource or exhausting it (full
database connection pools).
Solution: Whenever a resource is opened close it in the
finally block.
Prior to Java SE 7 all the objects which
implements java.io.Closeable must be
closed otherwise they will keep using
resources, from java 7 onwards this is
leveraged by java.lang.AutoCloseable
//continues from the previous slide
finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//continues from the previous slide
//In solution number 2 a new FileInputStream was opened the compiler won’t
issue a compilation error but when the app needs the file again it will throw
a runtime exception
}
}
Bad coding practices examples (Cont. 5/5)
Problem: Excessive garbage allocation
When creating many short lived objects
the garbage collector executes
continuously, this degrades application
performance, for example since strings
are immutable each time a different
string is stored a new space in memory
is allocated.
Solution: Use mutable alternatives when instancing new
objects.
To prevent creation of new objects
while looping, alternative mutable
classes should be used in the example
is possible to replace StringBuilder
instead of String.
//App: count to one million
public class Bad {
public static void main(String[] args) {
String oneMillionCount = "";
for (int i = 0; i < 1000000; i++) {
oneMillionCount = oneMillionCount+ i+ ",";
}
System.out.println(oneMillionCount);
}}
//App: count to one million
public class Good {
public static void main(String[] args) {
StringBuilder oneMillionCountSB = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
oneMillionCount.append(i);
oneMillionCount.append(",");
}
System.out.println(oneMillionCount.toString());
}}
Thank you!
Gustavo Michael Carrion
Linkedin: https://www.linkedin.com/in/mikecarrion/
Twitter: @gusmcarrion
Github: https://github.com/GCarrion03
E-mail: gcarrion03@gmail.com
Ad

Recommended

Junit and cactus
Junit and cactus
Himanshu
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010
Stefano Paluello
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
solutionjug4
 
FAQ - why does my code throw a null pointer exception - common reason #1 Rede...
FAQ - why does my code throw a null pointer exception - common reason #1 Rede...
Alan Richardson
 
Testing Legacy Rails Apps
Testing Legacy Rails Apps
Rabble .
 
Embrace Unit Testing
Embrace Unit Testing
alessiopace
 
L2624 labriola
L2624 labriola
michael.labriola
 
Unit Testing 101
Unit Testing 101
Dave Bouwman
 
Test Driven Development
Test Driven Development
Anand Kumar Rajana
 
Why Unit Testingl
Why Unit Testingl
priya_trivedi
 
Living With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
WebStackAcademy
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
Anand Kumar Rajana
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
Deepak Singhvi
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
Hazem Saleh
 
JMockit
JMockit
Angad Rajput
 
Laravel Unit Testing
Laravel Unit Testing
Dr. Syed Hassan Amin
 
Unit test
Unit test
서울대학교 컴퓨터공학부 클라우드 및 모빌 시스템 연구실(Cloud & Mobile Systems Lab @ SNU)
 
Spring Certification Questions
Spring Certification Questions
SpringMockExams
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
7mind
 
JUnit Presentation
JUnit Presentation
priya_trivedi
 
Cursus phpunit
Cursus phpunit
Nick Belhomme
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
n|u - The Open Security Community
 
Unit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
Write testable code in java, best practices
Write testable code in java, best practices
Marian Wamsiedel
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
Perfomatix Solutions
 
Node.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 
Clean Code
Clean Code
swaraj Patil
 
Key points of good software programming
Key points of good software programming
Marcio Luis da Silva
 

More Related Content

What's hot (20)

Test Driven Development
Test Driven Development
Anand Kumar Rajana
 
Why Unit Testingl
Why Unit Testingl
priya_trivedi
 
Living With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
WebStackAcademy
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
Anand Kumar Rajana
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
Deepak Singhvi
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
Hazem Saleh
 
JMockit
JMockit
Angad Rajput
 
Laravel Unit Testing
Laravel Unit Testing
Dr. Syed Hassan Amin
 
Unit test
Unit test
서울대학교 컴퓨터공학부 클라우드 및 모빌 시스템 연구실(Cloud & Mobile Systems Lab @ SNU)
 
Spring Certification Questions
Spring Certification Questions
SpringMockExams
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
7mind
 
JUnit Presentation
JUnit Presentation
priya_trivedi
 
Cursus phpunit
Cursus phpunit
Nick Belhomme
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
n|u - The Open Security Community
 
Unit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
Write testable code in java, best practices
Write testable code in java, best practices
Marian Wamsiedel
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
Perfomatix Solutions
 
Node.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 
Living With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
WebStackAcademy
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
Deepak Singhvi
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
Hazem Saleh
 
Spring Certification Questions
Spring Certification Questions
SpringMockExams
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
7mind
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
n|u - The Open Security Community
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
Write testable code in java, best practices
Write testable code in java, best practices
Marian Wamsiedel
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
Perfomatix Solutions
 
Node.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg
 

Similar to Java bad coding practices (20)

Clean Code
Clean Code
swaraj Patil
 
Key points of good software programming
Key points of good software programming
Marcio Luis da Silva
 
Clean code, Feb 2012
Clean code, Feb 2012
cobyst
 
Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)
Shirish Bari
 
Clean code
Clean code
Khou Suylong
 
Clean code
Clean code
Simon Sönnby
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
André de Fontana Ignacio
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
10 Ways To Improve Your Code( Neal Ford)
10 Ways To Improve Your Code( Neal Ford)
guestebde
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code
ConSanFrancisco123
 
Java Code Review Checklist
Java Code Review Checklist
Mahesh Chopker
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2
saber tabatabaee
 
Java Tips, Tricks and Pitfalls
Java Tips, Tricks and Pitfalls
Maksym Chuhaievskyi
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patterns
Steven Smith
 
Paving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering Practices
Aman King
 
2 the essentials of effective java
2 the essentials of effective java
Honnix Liang
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Clean code presentation
Clean code presentation
Bhavin Gandhi
 
Key points of good software programming
Key points of good software programming
Marcio Luis da Silva
 
Clean code, Feb 2012
Clean code, Feb 2012
cobyst
 
Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)
Shirish Bari
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
André de Fontana Ignacio
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
10 Ways To Improve Your Code( Neal Ford)
10 Ways To Improve Your Code( Neal Ford)
guestebde
 
Java Code Review Checklist
Java Code Review Checklist
Mahesh Chopker
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2
saber tabatabaee
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patterns
Steven Smith
 
Paving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering Practices
Aman King
 
2 the essentials of effective java
2 the essentials of effective java
Honnix Liang
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Clean code presentation
Clean code presentation
Bhavin Gandhi
 
Ad

Recently uploaded (20)

Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Which Hiring Management Tools Offer the Best ROI?
Which Hiring Management Tools Offer the Best ROI?
HireME
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Which Hiring Management Tools Offer the Best ROI?
Which Hiring Management Tools Offer the Best ROI?
HireME
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
Ad

Java bad coding practices

  • 2. Introduction Aside from what is defined as conventional bad java coding practices such as variables/methods/package naming, code formatting, among others. There are some others that I had the chance to experience during my years as a JEE engineer that I would like to share. Therefore in the following slides I am going to explain five bad coding practices by giving a short description of the problem then showing a poorly implemented code snippet, on the other hand a suggestion on how to fix or prevent this issue will be given along with a code snippet containing the correct implementation.
  • 3. Bad coding practices examples Problem: Presentation layer has high coupling with business logic layer One of the principles of good software design is loose coupling, if the presentation layer for example the web application must have the business layer logic referenced in his classpath creates high coupling, which creates dependency making different jars dependant. Solution: Create interfaces within a new jar to be referenced from client applications. By exposing business logic methods through interfaces coupling is reduced this allows seamless modification of the business logic without having to tweak the clients, also a good practice is to put the entities along with these interfaces so it is possible to pass them as parameters. public interface IGoodAppController { //Client jar code public String calculateGoodness(ScheduledMachine schMach); } public class GoodAppController implements IGoodAppController { @Override //Business jar logic public String calculateGoodness(ScheduledMachine schMach) { return "All good!"; }} //Single jar logic public class BadAppController { public String calculateGoodness(ScheduledMachine schMach) { return "Im highly coupled to you now!"; } }
  • 4. Bad coding practices examples (Cont. 2/5) Problem: Hard coded environment dependant variables Hard coding variables can lead to application crashes while moving from development to test / production environments for example while looking for IPs that only exists on a given environment, furthermore if they are left in a .java file they will be compiled to an uneditable .class. Solution: Make a properties file for constants or store them in the database. By putting everything in a single place to change we can overcome this problem, by creating a .properties file: public class Good { public static final String DB_HOST = "ipaddr"; public static void main(String[] args) { Properties prop = new Properties(); InputStream input = null; String ipAddr; try { input = new FileInputStream("envconst.properties"); // load prop file prop.load(input); // get the property and print it ipAddr=prop.getProperty(DB_HOST); … //continues in the next slide Another alternative is to create within the catalog table of the database one catalog that holds all these variables. public class Bad { public static final String DB_HOST = "192.168.1.1"; public static void main(String[] args) { Properties prop = new Properties(); InputStream input = null; String ipAddr; try { ipAddr=DB_HOST; // set the property value … //continues in the next slide
  • 5. Bad coding practices examples (Cont. 3/5) Problem: Catching the Exception superclass Throwing a very general exception makes an application recovery almost impossible and increases debug complexity by making the source of the exception hard to trace, this can lead to frequent application crashes and extended application downtimes: Solution: Catch exceptions related to the sentences being executed in that block of code. Create a catch block for every kind of expected subclass exception and in the last block finally catch the Exception superclass so it's easier to identify the problem: //continues from the previous slide } catch (FileNotFoundException e){ System.out.println("File not found Exception"); //Short description of the exception e.printStackTrace(); //Print the trace to see what is wrong } catch (IOException ex) { System.out.println("I/O General Exception"); //A more general exception is thrown ex.printStackTrace(); } catch (Exception ex) { System.out.println("General Exception"); //The base Exception superclass will catch any other exception ex.printStackTrace(); } //continues from the previous slide } catch (Exception ex) { System.out.println("General Exception"); ex.printStackTrace(); }
  • 6. Bad coding practices examples (Cont. 4/5) Problem: Files cannot be accessed / cannot open any more database connections. If there is a file opened / being edited or a database connection opened, if a close statement is not issued the resource will remain open until the database times it out, preventing access to that resource or exhausting it (full database connection pools). Solution: Whenever a resource is opened close it in the finally block. Prior to Java SE 7 all the objects which implements java.io.Closeable must be closed otherwise they will keep using resources, from java 7 onwards this is leveraged by java.lang.AutoCloseable //continues from the previous slide finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } } //continues from the previous slide //In solution number 2 a new FileInputStream was opened the compiler won’t issue a compilation error but when the app needs the file again it will throw a runtime exception } }
  • 7. Bad coding practices examples (Cont. 5/5) Problem: Excessive garbage allocation When creating many short lived objects the garbage collector executes continuously, this degrades application performance, for example since strings are immutable each time a different string is stored a new space in memory is allocated. Solution: Use mutable alternatives when instancing new objects. To prevent creation of new objects while looping, alternative mutable classes should be used in the example is possible to replace StringBuilder instead of String. //App: count to one million public class Bad { public static void main(String[] args) { String oneMillionCount = ""; for (int i = 0; i < 1000000; i++) { oneMillionCount = oneMillionCount+ i+ ","; } System.out.println(oneMillionCount); }} //App: count to one million public class Good { public static void main(String[] args) { StringBuilder oneMillionCountSB = new StringBuilder(); for (int i = 0; i < 1000000; i++) { oneMillionCount.append(i); oneMillionCount.append(","); } System.out.println(oneMillionCount.toString()); }}
  • 8. Thank you! Gustavo Michael Carrion Linkedin: https://www.linkedin.com/in/mikecarrion/ Twitter: @gusmcarrion Github: https://github.com/GCarrion03 E-mail: [email protected]