Friday, September 11, 2009

Java coding - Some useful tips

I am listing some useful java coding techniques i have experienced.

Even though we have PMD,CPD,FindBugs code quality tools, we cannot follow all the rules strictly, because we have to go with project time lines too.

Here i am giving some code techniques which will be helpful for the developers to reduce bugs or improve performance or at least easy to make code changes.

1. Understand API well and use
e.g.
String - contains() and indexOf()
Always use contains method to find the presence of a character sequence.
Don't go for indexOf and checking if(index > -1).
Because this is what implemented in contains() method.
There is no use in writing the already written code (Reusage ???).

Use indexOf() only if you are going to use the index for some other purpose.

2. Define types , variables and method parameters as interfaces
Always try to use interfaces to declare variables and method parameters.
This will help you for effortless re-factoring.

e.g. Collections API

Set set = new HashSet();
public int add(Set values){}
public int mul(Set values){}

We all know HashSet won't allow duplicates and the order won't be maintained.

Suppose in future, if you want the insertion order to be maintained you will go for LinkedHashSet.
The only place you have to change is : Set set = new LinkedHashSet();

If you used concrete HashSet, you have to change at all the places.
LinkedHashSet set = new LinkedHashSet();
public int add(LinkedHashSet values){}
public int mul(LinkedHashSet values){}

3. Don't use member variables in private methods.
Try to avoid using member variables in private methods.
Your private method functionality may be required for some other class in future.
So if you are not accessing the member variables,
you can just move that method to utility/helper class as public method and reuse it for more than one class.


Will continue ...