Wednesday, 22 August 2012

Java coding best practices

Following are the java programming best practices. 

1) Javadoc comments should be added to the class as well as the methods.
2) Unused member variables should not be present in the classes.
3) Proper catch blocks should be added for exception handling instead of single Exception object handler.
4) Proper naming conventions should be used for variables, method and class names.
5) Instead of using hard coded strings, constants should be declared in a separate Constants class.
6) All database and file handlers should be properly closed when there is no further need for them.
7) No trailing spaces should be present in code lines.
8) Uniform coding standards for braces, loops, if-else, switch should be used across the application.
9) If similar logic is being used at multiple places then it should be declared in a helper class and called from multiple places.
10) A single method should not exceed 100 lines of code as it becomes difficult to maintain beyond that.
Split a single big method into multiple smaller methods.
11) Usage of API classes and methods should be encouraged instead of writing custom code for performing the same operations.
12) A single statement should not go beyond the viewable area of the editor or IDE and should be split across multiple lines.
13) Extra emphasis should be given on writing the unit test cases for the code which is going to be released.
14) The addition of any piece of code should not break existing functionality.
15) Usually a single database transaction can be done by writing the SQL query in multiple ways and there is a huge
difference in the performance of database transactions depending upon the way in which SQL query is written.
16) If a class has many member variables and the instance of that class can be initialized by initializing
only a partial number of variables then it is better to have static factory methods for initializing the
member variables instead of overloading the constructors.
17) Creating immutable class should be encouraged than mutable classes.
18) The best way to check if the String object is neither null nor empty string is to use the following code: if(“”.equals(str))
19) Add appropriate access specifiers to methods instead of marking all methods in a class as public.
20) Follow best practices suggested by any framework/library being used in the application like Spring, Struts, Hibernate, jQuery.

No comments:

Post a Comment