Thursday, November 1, 2012

Best Practices for JAVA Programming

If you are a java programmer and not following java best practices, you are not java professional in real world because only programming doesn't important but how you write optimized code is more important.

So here are some of the points which i thought to be publish which can help help to java beginners.

1) Don't create objects unnecessarily

 Creation of object is one of the most expensive operation if we talk about memory utilization and performance as well.

Look @ the below code :

public class States{

 private List states;
 
 public List getStates() {
  
  //initialize only when required
  if(null == states) {
   States= new ArrayList();
  }
  return states;
 }
}

2) Never declare class instance as a public

To declaring a class instance public, there might be security problem with your application.
Let say we are creating a array of some months which is fixed and if we declare as a public, it could be easily access by someone and can change those values which cause security problem.

So instead of declaring public you can use private modifier and can access by defining getter method but again this array can be accessible so what you can do is, you can return a clone of array.

Look @ the below code:

Bad practice :
public String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
Good Practice :
private String[] months={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"};
 public String[] getMonths() 
 {
 return months.clone(); 
 }

No comments:

Post a Comment