Tuesday, January 31, 2012

Useful Best Practices in Java

1. Always prefer to lazy initialization to Defer Creating Objects until we need them.

Object creation in Java is the most expensive operation in terms of memory utilization and performance impact. Hence it is advised to create or initialize the Object only when it is required in the code.

public class myClass {
private mySampleObject myObj;
public mySampleObject getSampleObject() {
if (null == myObj)
myObj = new mySampleObject();

return myObj;

The advice for lazy initialization from Joshua Bloch is:
"Don't do it unless you need to."

The great majority of your initialization code should look like this:

// Normal initialization, not lazy!
private final FieldType field = computeFieldValue();

If you need lazy initialization for correctness -- but not for performance -- just use a synchronized accessor. It's simple and clearly correct.

If you need better performance, your best choice depends on whether you're initializing a static field or an instance field. If it's a static field, use the lazy initialization holder class idiom:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
static FieldType getField() { return FieldHolder.field; }

This idiom is almost magical. There's synchronization going on, but it's invisible. The Java Runtime Environment does it for you, behind the scenes. And many VMs actually patch the code to eliminate the synchronization once it's no longer necessary, so this idiom is extremely fast.

If you need high-performance lazy initializing of an instance field, use the double-check idiom with a volatile field. This idiom wasn't guaranteed to work until release 5.0, when the platform got a new memory model. The idiom is very fast but also complicated and delicate, so don't be tempted to modify it in any way. Just copy and paste -- normally not a good idea, but appropriate here:

// Double-check idiom for lazy initialization of instance fields.
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field;
if (result == null) // Second check (with locking)
field = result = computeFieldValue();
return result;

2. Use Private Fields. Never make an instance field of a Class Public.

Making a field private protects it from unsynchronized access. Controlling its access means the field need to be synchronized only in the class's critical sections when it is being modified.

Making a class field private can introduce lot of issues. For example, if we have a class called MyClass contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!
public class MyCalender {

public String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};


Best approach as many of you already know is to always make the field private and add a getter method to access the elements.
private String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};

public String[] getWeekdays() {
return weekdays;

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.
public String[] getWeekdays() {
return weekdays.clone();
3. Always try to minimize the mutability of a class.

Immutable means the state of the object cannot be changed, therefore an object with no accessors to the field is immutable (if none of the methods change the state either). Hence, the class is immutable means unmodifiable.

Its easy to maintain immutable classes because they not be modifiable hence thread safe. The data the class carries stays the same through out the lifetime of the class.

However, making an object immutable can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.
public class Employee {

private String firstName;
private String lastName;

public String getFirstName(){
return this.firstName;

public String getLastName(){
return this.lastName;

4. Prefer Interfaces over Abstract classes.
5. Always Try to limit the scope of the local variables.

Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.

Thus, declare a variable only when needed just before its use.

Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.

6. Try to use Standard libraries instead of writing on own from Scratch.

Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.

7. Use Strings with utmost care.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.

Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:
//slow instantiation
String slow = new String("Yet another string object");

//fast instantiation
String fast = "Yet another string object";

8. Defensive copies are savior.

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.
public static void main(String []arg) {

Date birthDate = new Date();
Student student = new Student(birthDate);



Now we may have some other code that uses the Student object.
public static void main(String []arg) {

Date birthDate = new Date();
Student student = new Student(birthDate);



In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!

To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.
public Student(birthDate) {
this.birthDate = new Date(birthDate);

This ensure we have another copy of birthdate that we use in Student class.

9. Never let exceptions come out of "finally" block.

Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out..