SlideShare uma empresa Scribd logo
1 de 8
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsWebStackAcademy
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.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 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Hazem Saleh
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification QuestionsSpringMockExams
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit7mind
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable coden|u - The Open Security Community
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practicesMarian Wamsiedel
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix Solutions
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practicesYoni Goldberg
 

Mais procurados (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018Mockito 2.x Migration - Droidcon UK 2018
Mockito 2.x Migration - Droidcon UK 2018
 
JMockit
JMockitJMockit
JMockit
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Unit test
Unit testUnit test
Unit test
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practices
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
 

Semelhante a Java bad coding practices

Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 featuresshrinath97
 
Features java9
Features java9Features java9
Features java9srmohan06
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017Ayush Sharma
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answersbestonlinetrainers
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Amit Singh
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Decompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationDecompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationJames Hamilton
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Icpc2010 bettenburg
Icpc2010 bettenburgIcpc2010 bettenburg
Icpc2010 bettenburgSAIL_QU
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShareyayao
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 

Semelhante a Java bad coding practices (20)

Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Features java9
Features java9Features java9
Features java9
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Decompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationDecompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 Presentation
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
J Unit
J UnitJ Unit
J Unit
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Icpc2010 bettenburg
Icpc2010 bettenburgIcpc2010 bettenburg
Icpc2010 bettenburg
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 

Último

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 

Último (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

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: gcarrion03@gmail.com