The following can be mentioned as some of the best practices to follow in a Java based project.
Most of these items , I have personally encountered in my previous projects and some I learned it the hard way.I will explain individually on importance of each one of these in future posts.
- Provide meaningful descriptions for every class and method.
- Import Statement should be as minimal and as narrow as possible.
- All class variables and method variables should be initialized with base values.
- For any operation on String, Null Check should be mandatory to avoid Null Pointer Exception.
- Any connection obtained should cleared and closed.
- Always close streams.
- Stored Procedures always preferrable compared to SQL queries from Java.
- In case of more than 3-4 ‘if’ conditions a case statement will be better choice.
- Don’t initialize String values with “null”.
- After catching exceptions don’t consume it, throw the exceptions to base class/ handle it.
- Use the framework used in the application. MVC is generally followed in most applications and validate this with existing code.
- All user inputs should be validated using Javascript.
- Do not use any class which is copyrighted and we don’t have access/permission/ability to change the source code.
- While using String operations StringBuffer is always preferred over a String “+” operation.
- No hard coding for userIds or security Strings. Use property files.
- Code should not have any System.out.println statements, this will affect performance in server. User logger instead.
- Commented code and unused code should be removed and cleared.
- While using RAD/Ecipe/WSAD use formatter tool to format your code. Set the parameters for line maximum length and this will give a readable code.
- In JSPs use style classes effectively this will save time when changing the look and feel.Do not enter values in tag elements, which can be declared in a style class.
- Use existing code/functions for achieving most operations, this will save time and create a standard way of coding.
- Do not use drprecated classes/methods. These functions will stop working in future Java revisions.
- Write reusable classes, which can be used in multiple screens/functions.
- Define a valid failure case in struts config.
- Passing arguments by reference will save memory and improve performance if there are multiple calls for the same method.