Java coding standards

1.Synchronized classes Vector,Hashtable,Stack and StringBuffer should not be used:

Early classes of Java API ,such as Vector,hashtable,StringBuffer  were synchronized to make  them thread safe.Unfortunately ,synchronization has a big negative impact on performance,even when using these collections from single threaded environment.It is better to use their non synchronized replacements.

  • ArrayList or LinkedList instead of Vector
  • Deque instead of stack
  •  HashMap instead of HashTable
  • StringBuilder instead of StringBuffer
2.Collection.isEmpty should be used  to test for emptiness:

Using Collection.size() to test for emptiness works but it has significant performance issue.Instead of Collection.size(),we should go for Collection.isEmpty() as its time complexity is O(1) whereas Collction.size() has complexity of O(n).

3.Empty array or collections should be returned instead of null:

Returning null instead of actual array or collection forces callers of the method to explicitly test for null ,making them more complex and less readable.
So instead of this below code,
public static List<Result> getResults() {
  return null;                             // Noncompliant
}

use this one,
public static List<Result> getResults() {
  return Collections.emptyList();          // Compliant
}


4.Return of boolean expressions should be wrapped into if then else statement:

Instead of below code ,
if(age > 18){
return true;
}else{
return false;
}
Preferable one is,
return (age>18)

5.Method parameters,caught exceptions and foreach variables should not reassigned:

While it is technically correct to assign to parameters from method bodies .it reduces code readability .Instead all parameters should be treated as final.
Instead of below code,
public int add(int a, int b) {
    a = a + b;                      // Noncompliant
    /* additional logic */
    return a;                       // Seems like the parameter is returned as is, what is the point?
  }

Below one is preferable,
 public int add(int a, int b) {
    return a + b;                   // Compliant
  }

Comments