Friday 1 April 2016

Java Optimization Rules

Use String length to compare empty string variables

It is quicker to test if the length of the string is 0. Because the String.equals() method is overkill to test for an empty string. 

Example: 

//VIOLATION
package com.vimal.sample;
public class SampleViolation {
  public boolean isEmpty(String s){
    return s.equals("");// VIOLATION
  }
}


//CORRECTION
package com.vimal.sample;
public class SampleCorrection {
public boolean isEmpty(String s){
return s.length()==0;// CORRECTION
}
}

Avoid duplication of code

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample() {
int x = 18;
if(x > 11) { // Violation.
        int jj = i + 9;
int k = jj * 3;
System.out.println(k);
}
else if( x < 30 ) { // Violation.
int jj = i + 9;
int k = jj * 3;
System.out.println(k);
}
}
}

Avoid empty "if" block structure

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample() {
int s = 0;
int i = 10;
if (i < s) {// VIOLATION
}
i = s;
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
public void sample() {
int s = 0;
int i = 10;
/*
if (i < s) {// CORRECTION
}
*/
i = s;
}
}


Avoid Serialized class with only transient fields

The class with only transient fields doesn't have any state information that needs to be preserved



Example: 



package com.vimal.sample;

import java.io.Serializable;

public class SampleViolation implements Serializable { //Violation

transient int count = 0;

}


Should be written as:


package com.vimal.sample;

import java.io.Serializable;

public class SampleCorrection { //Correction

transient int count = 0;

}



Avoid using Math class methods on constants


It is quicker to determine the value statically.

Example: 

public class SampleViolation {
public void sample() {
double a;
a = Math.abs(2.5); // VIOLATION
}
}

Should be written as:

public class SampleCorrection {
public void sample() {
double a;
a =2.5; // FIXED

}

}

Avoid polling loops

Do not use polling loops / busy waiting.

Example: 

package com.vimal.sample;

public class SampleViolation {
boolean c;
void sample() {
while(!c) {
try {
Thread.sleep(100); // VIOLATION
}
catch (InterruptedException e){ 
    }
}
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
boolean c
Object obj; 
void sample() {
synchronized(obj) {
while(!c) {
try {
objLock.wait(); // CORRECTION
}
catch (InterruptedException e) { 
}
}
}
}

}

Avoid multi dimensional arrays

Try to use single dimensional arrays in place of multidimensional arrays.

Example: 


package com.vimal.sample;
public class SampleViolation {
public void sample(int[][] val) { // VIOLATION
for (int i = 0; i < val.length; i++) {
System.out.println(val[i][0] + ":" + val[i][1]);
}
}
public void sampleAlt() {
int[][] arr = new int[][]{ // VIOLATION
{1,2}, {2,4}, {3,6}, {4,8}
};
sample(arr);
}


}

Should be written as:


package com.vimal.sample;
public class SampleCorrection {
public void sample(int[] val1, int[] val2) { // CORRECTION
for (int i = 0; i < val1.length; i++) {
System.out.println(val[i] + ":" + val[i]);
}
}
public void sampleAlt() {
int[] arr1 = new int[]{1,2,3,4}; // CORRECTION
int[] arr2 = new int[]{2,4,6,8}; // CORRECTION
sample(arr1, arr2);
}


}

Define initial capacities

Expansion of array capacity involves allocating a larger array and copying the contents of the old array to a new one.

The old array object gets reclaimed by the garbage collector. Array expansion is an expensive operation.

Example: 

package com.vimal.sample;
import java.util.ArrayList;
public class SampleViolation {
private ArrayList al = new ArrayList(); // VIOLATION
public int sample() {
return al.size();
}
}

Should be written as:

package com.vimal.sample;
import java.util.ArrayList;
public class SampleCorrection {
private final int s = 10;
private ArrayList al = new ArrayList(s); // CORRECTION
public int sample() {

return al.size();

}

}

Avoid Integer valueOf intValue


Avoid using Integer.valueOf(String).intValue() instead call Integer.parseInt(String).

Example: 

package com.vimal.sample;
public class SampleViolation {
public int getValue(String s) {
return Integer.valueOf(s).intValue(); // VIOLATION
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public int getValue(String s) {
return Integer.parseInt(s); // CORRECTION
}

}


Close jdbc connections

Always close the database connections opened.

Example: 

package com.vimal.rule;
public class SampleViolation {
public void sample (String url) throws SQLException {
try {
Connection conn = DriverManager.getConnection(url); // VIOLATION
// some operations on connection
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample (String url) throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
conn.close(); // CORRECTION
}
}
}

Close jdbc connections Only In finally Block

Always close the database connections opened. The one of the places to close the connection is in finally block.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample (String url) throws SQLException {
try {
Connection conn = DriverManager.getConnection(url);
conn.close (); // VIOLATION
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample (String url) throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (java.lang.Exception e) {
e.printStackTrace();
} finally {
conn.close(); // CORRECTION
}
}
}

Place try catch out of loop

Placing "try/catch/finally" blocks inside loops can slow down the execution of code.

Example: 

package com.vimal.sample;
public class SampleViolation {
void sample (InputStream is) {
int z = 0;
int t = 20;
int c = 0;
for (int i = z; i < t; i++) {
try {// VIOLATION
c += is.read();
} catch (IOException ie) {
ie.printStackTrace();
}
}
 }
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
  void sample (InputStream is) {
int z = 0;
int t = 20;
int c = 0;
try { // CORRECTION
for (int i = z; i < t; i++) {
c += is.read ();
}
} catch (IOException ie) {
ie.printStackTrace();
}
 }
}

Avoid string concatenation in loop

Use 'StringBuffer' instead of 'String' for non-constant strings.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample() {
String res = "";
for (int i = 0; i < 10; i++) {
res += i+","; // VIOLATION
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
String res = "";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 10; i++) {
buffer.append(i+","); // CORRECTION
}
res = buffer.toString(); // CORRECTION
}
}

Avoid repeated casting

Avoid repeated casting by casting it once and keeping its reference

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample(Object obj) {
((User) obj).setText(""); // VIOLATION
((User) obj).setEditable(false); // VIOLATION
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
public void sample(Object obj) {
final User tf = (User) obj; // CORRECTION
tf.setText("");
tf.setEditable(false);
}
}

Use toArray with array as parameter

Use toArray(Object[] ) instead of toArray() on collection.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample() {
Collection c = new ArrayList();
c.add("one");
c.add("tow");
Object[] obj  = c.toArray(); // Violation
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
Collection c = new ArrayList();
c.add("one");
c.add("two");
String[] x = (String[]) c.toArray(new String[2]); //Correction
}
}

Avoid using java lang Runtime freeMemory

Avoid using java.lang.Runtime.freeMemory() in production code since it is typically associated at the time of manual profiling activities.Use some profiling tool instead.

Example: 

public class SampleViolation {
public static void main(String[] args) {
System.out.println( Runtime.getRuntime().freeMemory() ); // VIOLATION
int[] val = new int[ args.length ];
for ( int i = 0; i < val.length; i++ ) {
val[ i ] = Integer.parseInt( args[ i ] );
}
System.out.println( Runtime.getRuntime().freeMemory() ); // VIOLATION
}
}

Use PreparedStatement instead of Statement

PreparedStatements should be used where dynamic queries are involved.

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample(Connection conn) throws Exception {
Statement stmt = conn.createStatement();
for (int i = 0; i < count; i++) {
String qry = "SELECT * FROM user WHERE id = " + i;
ReultSet rs = stmt.execute(qry);
.....
}
}
}

Should be written as:

package com.rule;

public class SampleCorrection {
public void sample(Connection conn) throws Exception {
String qry = "SELECT * FROM user WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement(qry);
for (int i = 0; i < count; i++) {
pstmt.setString(1,""+i);
ResultSet rs = pstmt.executeQuery();
.....
}
}
}

Close jdbc resources

Always close the JDBC resources opened.The place to close jdbc resources is finally block

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample(String url, String query) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url);
stmt = conn.createStatement(); // VIOLATION
rs = stmt.executeQuery(query); // VIOLATION
} catch (Exception e) {
}finally{
try {
conn.close();
} catch (Exception e){
}
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample(String url, String query) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
} catch (Exception e) {
} finally{
try {
rs.close(); // CORRECTION
stmt.close(); // CORRECTION
conn.close();
} catch (Exception e){
}
}
}
}

Avoid concatenating Strings in StringBuffer

Avoid concatenating Strings in StringBuffer's constructor or append(..) method.

Example: 

public class SampleViolation {
public void sample() {
StringBuffer sb = new StringBuffer("Hi" + getGames()); // VIOLATION
sb.append("he is " + getUserName()); // VIOLATION
}
}

Should be written as:

public class SampleCorrection {
public void sample() {
StringBuffer sb = new StringBuffer("Hi");
sb.append(getGames());
sb.append("He is ");
sb.append(getUserName());
}
}

Stream_not_closed

Always close the streams opened, in finally block.

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample (java.io.File f) throws IOException {
FileInputStream fileInputStream = null;
try {
fileInputStream = new java.io.FileInputStream(f); //Violation
fileInputStream.read ();
} catch (java.io.FileNotFoundException e1) {

}
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
public void sample (java.io.File f) throws IOException {
FileInputStream fileInputStream = null;
try {
fileInputStream = new java.io.FileInputStream(f);
fileInputStream.read ();
} catch (java.io.FileNotFoundException e1) {

} catch (java.lang.Exception e) {

} finally {
fileInputStream.close (); // CORRECTION
}
}
}

Use NIO in server

Using NIO for server is better than using traditional java.net package.

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample(ServerSocket ss) throws IOException {
Socket soc = ss.accept(); // VIOLATION
}
}

Should be written as:

Use classes in java.nio.channels in the server code.












Specify StringBuffer capacity


The Default 'StringBuffer' constructor will create a character array of a default size(16). When size exceeds its capacity, it has to allocate a new character array with a larger capacity, it copies the old contents into the new array,

and eventually discard the old array.By specifying enough capacity during construction prevents the 'StringBuffer' from ever needing expansion.



Example: 



package com.vimal.sample;



public class SampleViolation {

private StringBuffer sb = new StringBuffer(); // VIOLATION

public void method(int i) {

sb.append(i);

}

}



Should be written as:



package com.vimal.sample;



public class SampleCorrection {

private final int size = 10;

private StringBuffer sb = new StringBuffer(size); // CORRECTION

public void sample(int i) {

sb.append(i);

}

}

Avoid constant expressions in loops

It is more efficient to either simplify these expressions or move them outside the body of the loop.



Example: 



public class SampleViolation {

 public static final boolean TRUE= true;

 public static final boolean FALSE= false;

 public static final int sample= 7;

 public void sample() {

  int[] x= new int[10];

  int j= 0;

  for(int i=0; i<10; i++) {

x[0]= 7+(sample+9);// VIOLATION

for(j=0; TRUE||FALSE;) {// VIOLATION


}

  }

 }

}



Should be written as:



public class SampleCorrection {

 public static final boolean TRUE= true;
 public static final boolean FALSE= false;
 public static final int sample= 7;

 public void sample() {

  int[] x= new int[10];

  int j= 0;

  x[0]= 7+(sample+9);//Correction

  for(int i=0; i<10; i++) {

for(j=0; TRUE;) {//Correction



}

  }

 }

}

Reduce switch density

Reduce switch density for performance reasons.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample() {
switch (x) { // Violation.
case 1: {
if(status) {
// More Statements
}
  break;
}
case 2: {
// More Statements
break;
}
default : {
 
}
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
switch (x) { //Correction.
case 1: {
if(status) {
method1();
}
  break;
}
case 2: {
method2();
break;
}
default : {
 
}
}
}
public method1() {
// Do Something.
}
public method2() {
// Do Something.
}
}

Avoid unnecessary implementing Clonable interface

Example: 

package com.vimal.sample;
public class Sampleviolation implements Clonable {
public void sample() {//Violation.
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection implements Clonable {
public void sample() {
Sampleinterface clone = new Sampleinterface();
Object o = theClone.clone(); //Correction.
}
}

Avoid new with string


Avoid using new with String objects.



Example: 



package com.vimal.sample;

public class SampleViolation {

public int sample(String str) {

String s = new String(str); // VIOLATION

return s.length();

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

public int sample(String str) {

String s = str; // CORRECTION

return s.length();

}

}

Use arrayList inplace of vector


Use 'ArrayList' in place of 'Vector' wherever possible ArrayList is faster than Vector except when there is no lock acquisition required in HotSpot JVMs (when they have about the same performance)



Example: 



package com.vimal.sample;

public class SampleViolation {

  final int SIZE = 10;

  private Vector v = new Vector(SIZE); // VIOLATION

  public int sample() {

return v.size();

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

final int SIZE = 10;

private ArrayList al = new ArrayList(SIZE);// CORRECTION

public int sample() {

return al.size();

}

}

Avoid Synchronized blocks


Do not use synchronized blocks to avoid synchronization overheads



Example: 



package com.vimal.sample;

public class SampleViolation {

public void sample() {

synchronized (getClass()) { // VIOLATION

.....

}

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

public synchronized void doTest() { // CORRECTION

.....

}

}

Use hashMap inplace of hashTable


Use 'HashMap' in place of 'HashTable' wherever possible



Example: 



public class SampleViolation {

private static final int SIZE = 10;

private Hashtable ht = new Hashtable(SIZE); // VIOLATION

public void sample() {

ht.clear();

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

private static final int SIZE = 10;

private HashMap ht = new HashMap(SIZE); // CORRECTION

public void sample() {

ht.clear();

}

}

Declare method arguments final


Any method argument which is neither used nor assigned should be declared final.



Example: 



package com.vimal.sample;

public class SampleViolation {

public void sample(int i,int j) {  // VIOLATION

j = j + i;

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

public void sample(final int i,int j) {  // CORRECTION

j = j + i;

}

}

Avoid using java lang Class forName


Decreases performance and could cause possible bugs.



Example: 



public class SampleViolation {

private void sample() {

try {

System.out.println(Class.forName("java.lang.Integer").getName()); // VIOLATION

} catch ( ClassNotFoundException e ) {

e.printStackTrace();

}

}

}



Should be written as:



public class Sample {

private void sample() {

System.out.println(java.lang.Integer.class.getName()); // CORRECTION

}

}

Declare variable final


Any variable that is initialized and never assigned to should be declared final.



Example: 



package com.vimal.sample;

public class SampleViolation {

public void sample() {

int i = 5;  // VIOLATION

int j = i;

j = j + i;

}

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

public void sample() {

final int i = 5;  // CORRECTION

int j = i;

j = j + i;

}

}

Always declare constant field static


The constant fields that are declared final should be declared static.



Example: 



package com.vimal.sample;

public class SampleViolation {

final int MAX = 1000; // VIOLATION

final String NAME = "Noname"; // VIOLATION

}



Should be written as:



package com.vimal.sample;

public class SampleCorrection {

static final int MAX = 1000; // CORRECTION

static final String NAME = "Noname"; // VIOLATION

}

Avoid_unnecessary_instanceof

Avoid unnecessary "instanceof" evaluations.

Example: 

package com.vimal.sample;

public class SampleViolation {
private String obj = "hi"; 
public void sample() {
if (obj instanceof Object) { // VIOLATION
obj.getClass();
}
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
private String obj = "hi"; 
public void sample() {
/* // CORRECTION
if (obj instanceof Object)
{
obj.getClass();
}
*/
obj.getClass();
}
}

Use instanceof only on interfaces

Example: 

public class MyClass { 
}

public class SampleViolation {
 private void sample (Object o) {
  if (o instanceof MyClass) { }// VIOLATION
 }
}

Should be written as:

package com.vimal.sample;

interface MyInterface {
}

public class MyClass implements MyInterface {
}

public class SampleCorrection {
 private void sample (Object o) {
  if (o instanceof MyInterface) { 
  }// Correction
 }
}

Avoid creating thread without run method

A Thread which is created without specifying a run method does nothing other than a delay in performance.

Example: 

public class SampleViolation {
 public void sample() throws Exception {
  new Thread().start();  //VIOLATION
 }
}

Should be written as:

public class SampleCorrection {
 public void sample(Runnable r) throws Exception {
  new Thread(r).start();  //FIXED
 }
}

Do not declare members accessed by inner class private

Do not declare members accessed by inner class private.

Example: 

public class SampleViolation {
private int iVar = 0; // Violation
class inner {
int var2;
public void sample() {
var2 = iVar;
// ...
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
int iVar = 0; // Correction
class inner {
int var2;
public void sample() {
var2 = iVar;
// ...
}
}
}

Avoid passing primitive int to Integer constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class Sample {
public void sample() {
Integer i = new Integer(3); // VIOLATION
//...
}
}

Should be written as:

public class Sample {
public void sample() {
Integer i = Integer.valueOf(3); // Correction
//...
}
}

Avoid passing primitive long to Long constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class SampleViolation {
public void sample() {
Long i = new Long(3); // VIOLATION
//...
}
}

Should be written as:

public class SampleCorrection {
public void sample() {
Long i = Long.valueOf(3); // CORRECTION
//...
}
}

Avoid passing primitive char to Character constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class SampleViolation {
public void sample() {
Character i = new Character('a'); // VIOLATION
//...
}
}

Should be written as:

public class SampleCorrection {
public void sample(){
Character i = Character.valueOf('a'); // CORRECTION
//...
}
}

Avoid using String toString

Avoid calling toString() on Strings.Instead use String.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample() {
String str="sample";
System.out.println(str.toString()); // Violation.
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
String str="sample";
System.out.println(str); // Correction
}
}

Avoid passing primitive byte to Byte constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class Sample {
public void sample() {
Byte i = new Byte(3); // VIOLATION
//...
}
}

Should be written as:

public class Sample {
public void sample() {
Byte i = Byte.valueOf(3); // FIXED
//...
}
}

Avoid passing primitive double to Double constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class Sample {
public void sample() {
Double i = new Double(3.0); // VIOLATION
//...
}
}

Should be written as:

public class Sample {
public void sample(){
Double i = Double.valueOf(3.0); // CORRECTION
//...
}
}

Avoid passing primitive short to Short constructor

Avoid creating objects of primitive types using the constructor.

Example: 

public class Sample {
public void sample() {
Short i = new Short(5); // VIOLATION
//...
}
}

Should be written as:

public class Sample {
public void sample() {
Short i = Short.valueOf(5); // CORRECTION
//...
}
}

Avoid nested Synchronized blocks

Avoid nested Synchronized blocks to improve performance

Example: 

public class SampleViolation {
public void sample() {
//......
synchronized (getClass()) {
//.....
synchronized (this) { // VIOLATION
//.....
}
//.....
}
//......
}
}

Reduce number of exception creations

Reduce number of exception creations for performace reasons

Example: 

public class SampleViolation {

public static final int TEN = 10;
public void sample() throws Exception {
if(true)
{
throw new Exception("1");
}
if(true)
{
throw new Exception("2");
}
if(true)
{
throw new Exception("3");
}
if(true)
{
throw new Exception("4");
}
if(true)
{
throw new Exception("5");
}
if(true)
{
throw new Exception("6");
}
if(true)
{
throw new Exception("7");
}
if(true)
{
throw new Exception("8");
}
if(true)
{
throw new Exception("9");
}
if(true)
{
throw new Exception("10");
}
if(true)
{
throw new Exception("11");// VIOLATION, it is the 11th exception.
}
}
}

Should be written as:

public class SampleCorrection {

public static final int TEN = 10;
public void sample() throws Exception {
if(true)
{
throw new Exception("1");
}
if(true)
{
throw new Exception("2");
}
if(true)
{
throw new Exception("3");
}
if(true)
{
throw new Exception("4");
}
if(true)
{
throw new Exception("5");
}
if(true)
{
throw new Exception("6");
}
if(true)
{
throw new Exception("7");
}
if(true)
{
throw new Exception("8");
}
if(true)
{
throw new Exception("9");
}
if(true)
{
throw new Exception("10");
}
// CORRECTION.
}
}

Ensure efficient iteration over map entries

Using a keyset to iterate over a map, and then requesting values for each key is inefficient.

Example: 

public class SampleViolation {
 public void Sample(Map map)
 {
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
Object key = iter.next();
Object value = map.get(key); // VIOLATION
  }
 }
}

Should be written as:

public class SampleCorrection {
 public void sample(Map map)
 {
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue(); // CORRECTION
  }
 }
}

Ensure efficient removal of map entries

Searching a keyset/entryset to fetch the key to remove the element is inefficient.

Example: 

public class SampleViolation {
 public void sample(HashMap collection) {
  Set keySet = collection.keySet();
  Iterator keyIter = keySet.iterator();
   while (keyIter.hasNext()) {
    Object key = keyIter.next();
    collection.remove(key); // VIOLATION
   }
 }
}

OR
another case when we iterate on entry set:


public class SampleViolation {
 public void sample(HashMap collection) {
  Set entrySet = collection.entrySet();
  Iterator entriesIter = entrySet.iterator();
   while (entriesIter.hasNext())  {
    Map.Entry) entry = (Map.Entry)entriesIter.next();
    Object key = entry.getKey();
    collection.remove(key); // VIOLATION
   }
 }
}

Should be written as:

public class SampleCorrection {
 public void sample(HashMap collection)  {
  Set keySet = collection.keySet();
  Iterator keyIter = keySet.iterator();
   while (keyIter.hasNext()) {
    keyIter.remove(); // CORRECTION
   }
 }
}

Always reuse immutable constant objects for better memory utilization

Creation of constant immutable objects that are not assigned to static final variables lead to unnecessary memory consumption.

Example: 

public class SampleViolation {
  protected Object[] getObjects() {
  return new Object[0];  // VIOLATION
  }
  public static Integer sample(String s) {
  if (s == null || s.length() == 0) {
return new Integer(-1);  // VIOLATION
} else {
return new Integer(s);
}
 }
}

Should be written as:

public class SampleCorrection {
 public static final Object[] NO_OBJECTS = new Object[0];
 protected Object[] getObjects() {
  return NO_OBJECTS;  // CORRECTION
 }
 private static final Integer INT_ = new Integer(-1);
 public static Integer sample(String s) {
if (s == null || s.length() == 0) {
return INT_;  // CORRECTION
} else {
return new Integer(s);
}
 }
}

Avoid instantiation for getClass

Do not create instances just to call getClass on it.

Example: 

package com.vimal.sample;

public class SampleViolation {
public void sample() {
Class c = (new ClassSample()).getClass(); // VIOLATION
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
public void sample() {
Class c = ClassSample.class; // CORRECTION
}
}

Avoid equality with boolean

Avoid comparing a boolean with "true".

Example: 

public class SampleViolation {
boolean sample(String value) {
boolean b = false;
String str = "S";
if (value.endsWith(str) == true) {// VIOLATION
b = true;
}
return b;
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
boolean sample(String value) {
boolean b = false;
String str = "A";
//....
//........
if ( value.endsWith(str) ) { // CORRECTION
b = true;
}
return b;
}
}

Avoid call to Thread.sleep()

Do not call Thread.sleep() for performance reasons

Example: 

public class SampleViolation {
public void sample() {
Thread.sleep(100); // VIOLATION
}
}

Should be written as:

package com.vimal.sample;
public class sampleCorrection {
public void sample() {
this.wait(100); // CORRECTION
}
}

Avoid creating double from string

Avoid creating double from string for improved performance

Example: 

public class SampleViolation {

public void sample() {
Double db = new Double("3.44");  // VIOLATION
Double.valueOf("3.44"); // VIOLATION
if(db == null) {
// Do Something
db = null;
}
}
}

Should be written as:

Avoid converting String to Double

Avoid using String charAt

Use char[] representation of the string instead of using String.charAt().

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample(String str) {
for(int i=0; i<str.length(); i++) {
System.out.println(str.charAt(i)); // VIOLATION
}
}
}

Should be written as:

package com.vimal.sample;
class SampleCorrection {
public void Sample(String str) {
char[] carr = str.toCharArray(); // CORRECTION
for(int i=0; i<carr.length; i++) {
System.out.println(carr[i]); // CORRECTION
}
}
}

Avoid using exponentiation

Do not use exponentiation.

Example: 

package com.vimal.sample;

public class SampleViolation {
public int getPower(int iB, int iP) {
int it = (int) Math.pow(iB, iP); // VIOLATION
return it;
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection {
public int getPower(int iB, int iP) {
int it = 1;
for (int i = 0; i < iP; i++) { // CORRECTION
it *= iB;
}
return it;
}
}

Avoid using Double toString

Avoid using Double toString for performance reasons

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample(double d) {
String dStr = Double.toString(d); // VIOLATION
System.out.println(dStr);
}
}

Should be written as:

Avoid Using Double.toString() instead use custom conversion algorithm.

Avoid LinkedLists

Avoid LinkedLists instead use Vector / ArrayList as LinkedList implementation has a performance overhead for indexed access.

Example: 

package com.vimal.sample;
public class ClassViolation {
public void sample() {
LinkedList list = new LinkedList();
if(list != null) {
list = null;
}
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
final int SIZE = 10;
ArrayList list = new ArrayList(SIZE);
if(list != null) {
list = null;
}
}
}

Declare public or protected method final

It optimizes the code and makes the code self documenting.

Example: 

class SampleViolation{
public void sample() { // VIOLATION
}
}

Should be written as:

class SampleCorrection {
public final void method() { // CORRECTION
}
}

Declare private constant fields final

A private constant fields should be declared final for performance reasons

Example: 

package com.vimal.sample;

class SampleViolation {
private int i = 5;  // VIOLATION
public void sample() {
int j = i;
j = j + i;
}
}

Should be written as:

package com.vimal.sample;

class SampleCorrection {
private final int i = 5;  // CORRECTION
public void sample() {
int j = i;
j = j + i;
}
}

Do lazy initialization

Example: 

package com.vimal.sample;
public class SampleViolation {
private Classviolation  instance  =  new Classviolation();  //Violation
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
private ClassViolation instance;
public ClassVoliation getInstance()
{
if(doLazy == null)
instance  =  new ClassViolation();  // Correction
return instance;
}
}

Use entrySet instead of keySet

Use entrySet() instead of keySet().

Example: 

public class SampleViolation {
public void sample() {
Map m = new HashMap();
Iterator it = m.keySet().iterator();
Object key = it.next();
Object v = m.get(key); // Violation
}
}

Should be written as:

package com.vimal.sample;

public class SampleCorrection
{
public void sample()
{
Map m = new HashMap();
Set set = m.entrySet(); //Correction.
Object keyValuePair = it.next();
}
}

Avoid boolean array

Do not use array of boolean.

Example: 

package com.vimal.sample;
public class SampleViolation {
public void sample() {
boolean[] b = new boolean[]{true, false, true}; // VIOLATION
}
}

Should be written as:

package com.vimal.sample;
public class SampleCorrection {
public void sample() {
BitSet bs = new BitSet(3); // CORRECTION
bs.set(0);
bs.set(2);
}
}

Loop invariant code motion

The code that is going to result in same value over the iterations of loop, should be moved out of the loop.

Example: 

package com.vimal.sample;
class SampleViolation {
public void sample(int x, int y, int[] z) {
for(int i = 0; i < z.length; i++) {
z[i] = x * Math.abs(y); // VIOLATION
}
}
}

Should be written as:

package com.vimal.sample;
class SampleCorrection {
public void sample(int x, int y, int[] z) {
int t1 = x * Math.abs(y); // CORRECTION
for(int i = 0; i < z.length; i++) {
z[i] = t1;
}
}
}

Use System arrayCopy

Use 'System.arraycopy()' instead of a loop to copy array. This rule disallows the copying of arrays inside a loop

Example: 

package com.vimal.sample;
class SampleViolation {
public int[] copyArray (int[] array) {
int length = array.length;
int[] copy = new int [length];
for(int i=0;i<length;i++) {
copy [i] = array[i]; // VIOLATION
}
return copy;
}
}

Should be written as:

package com.vimal.sample;
class SampleCorrection {
public int[] copyArray (int[] array) {
final int ZERO = 0;
int length = array.length;
int[] copy = new int [length];
System.arraycopy(array, ZERO, copy, ZERO, length); // CORRECTION
return copy;
}
}

Avoid debugging code


Avoid debugging code.


Example: 

package com.vimal.sample;
public void SampleVolation {
private int count =0;
public int getCount() {
//...
System.out.println("count ="+count);  // Violation
return count;
}
}

Should be written as:

package com.vimal.sample;
public void SampleCorrection {
private int count =0;
public int getCount() {
if (Debug.ON) {
System.out.println("count ="+count);  //correction
}
return count;
}
}

Ensure efficient removal of elements in a collection


Searching a collection to fetch the element to remove is inefficient.

Example: 

public class Sample {
public void sample(Collection collection) {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
Object element = iter.next();
collection.remove(element); // VIOLATION
}
}
}

Should be written as:

public class Sample {
public void someMethod(Collection collection) {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
iter.remove(); // CORRECTION
}
}
}



Enjoy.....................
Reference:

2 comments:

  1. I am java beginner. This is really useful post! Thank you....

    Please write about threads also........

    ReplyDelete
  2. thanks for this great article! This is really useful.

    ReplyDelete