SOA / Web Services / Java

A Technology Blog

Some Java Best Practices

Posted by Vivek on May 23, 2010

— Only one top level class should be defined per file.

— Visibility of variables, methods and class should be kept as minimum as possible.

— Import only required classes in your program.

— Do not use unused method, variables or classes. Make sure comments are used as per the java

coding standards. 

— Avoid using finalize method as garbage collection is not predictable.

— Every method should contain Java Doc and describe input and output parameters.
/**
         * <Method description goes here>
         *
         * @param parameter name description
         * @return return description
         * @throws exception decription
         */

— Use proper indentation. Make use of your IDE (eclipse, jedeveloper etc) which provides built-in features. For ex. Ctrl + Shift + F when using eclipse can help reduce checkstyle errors and improve indentations.
— Declare only one varible per line. For ex:
instead of
private int x = 10, int y = 20, int z = 30;
use
private int x = 10;
private int y = 20;
private int z = 30;

— All variables should be initialized before they are accessed. Use lazy initialization if you

want to initialize a variable only when it is needed.

— Declare and Use local variables within a method. Do not reuse the variable.

— Declare static variables private and provide a public/protected method for other objects to

access it. For ex:
private static int myAge;

public static int getMyAge() {
   return myAge;
}

— Use paranthesis to indicate operator precedence.

— Do not use hardcoded values in the program. Use constants files instead.

— Use null pointer checks wherever applicable.

— keep methods short. If possible, it should contain 25 statements or less. Try not to exceed 80 characters when coding a line of code.

— Always use curly braces for blocks of code especially if-else.

— Nesting should not be more than 3 levels if possible.

— Boolean values should be implicit in an if statement. For ex:
instead of
if(myFlag == true){…}
use
if(myFlag){..}

— use values on left side during comparisons to avoid any null pointer exception. For ex:
instead of
if((myMethod.getMyFirstName()).equals(“Henry”)){..}
use
if((“Henry”).equals(myMethod.getMyFirstName())){..}
if getMyFirstName() returns null in first expression, it will throw a NPE. This is avoided in

the second statement.

— Do not access a method through another method.For ex:
avoid this.getMyName().getMyFirstName();

— Use System.arraycopy( ) to copy an array.

— Always, set the size of collection objects. Use Set, List etc instead of HashSet, ArrayList etc.

— Class names must start with an Capital letter. Method and variable names should begin with lowercase. Exception classes must end with the word Exception. Use uppercase for all constant names and use underscore to seperate words (For ex: static final int MY_DATE_OF_BIRTH = 26;).

— A method should be declared abstract in a class which will not be instantiated. 

— Present exceptions to the user in a proper manner. Do not just catch and log exception, if

applicable. Do not use empty catch blocks or catch or throw the classes Throwable or Exception.
Use finally block for clean up activities and do not throw any exception from a finally block.
Try to classify exceptions as Business Exception and System Exception and deal accordingly.

— Avoid using multiple return statements in a method.

— Use synchronized method only if it is applicable. For example: Use StringBuilder if only one

thread is going to use it at a time instead of StringBuffer, which is synchronized.

— Avoid using StringTokenizer. Avoid methods like String.toUpperCase() and String.toLowercase( )

that copy the characters of the string.

— Use log4j or apache commons logging framework instead of System.out.print() statements.

— Logging at entry and exit methods must be at TRACE level.

— Use ThreadLocal to allow accessing states from a thread.

— Clone() method can be used to avoid invocation of constructors.

— Create objects early in the application and do not destroy until they are utilized completely.
 
— Avoid method calls from loops. Use inline statements even if it causes redundant code.

— Use short circuit operators instead of bit wise operators. For ex: && is better than &

— Use ? for an unknown object type. For ex:
instead of Collection<object> use Collection<?>

— Use annotations wherever applicable. For ex: @override to indicate that this method overrides a method, @SuppressWarnings to suppress warnings from compiler.

— Use caching if repeatedly accessing a constant piece of code or performing IO operation on a

constant file.

— Encourage use of Writing Junit test cases.

— Improve coverage of code. Use tools like EMMA, cobertura.

— Use checkstyle and PMD for improving layout of code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: