Friday, December 30, 2011

Creating Java Object -- Part-VI


This below discussion is not exactly about creating java objects but good practices after you create java object.

Eliminate obsolete object references

We know that in java, objects are automatically garbage collected, so we don’t give much attention on how objects are getting destroyed.  But sometimes memory leak can happen.  The reason behind this as the stack grows and then shrinks, the objects that were popped out from the stack will not be garbage collected even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects.  An obsolete reference is a reference that will never be dereferenced again. 
For e.g.
    public Object pop() {
        if(size == 0) {
               throw new EmptyStackException();
        }
        return result = elements[--size];
    }
In this case, any references outside of the “active portion” of the element array are obsolete.  The active portion consists of the elements whose index is less than size.
In order to solve this memory leak, we can nullify the object.
public Object pop() {
        if(size == 0) {
               throw new EmptyStackException();
        }
        object result = elements[--size];
        element[size] = null;
        return result;
    }
But it should be noticed that nullifying an object reference should be exception rather than the norm.  The best way to eliminate an obsolete reference is to let the variable that contained the reference fall out of scope.  This occurs automatically if each variable is defined in the narrowest possible scope.

Another source of memory leaks is caches.  We may put an object reference in cache and forget it. There may be many solutions for this.  One can be making the cache as WeakHashMap so that entries will be removed automatically after they become obsolete.

One more common source of memory leaks is listeners and other callbacks. Again the better way to keep safe in this situation is to keep weak reference by storing them only as keys in a WeakHasMap.

{Courtesy: Effective Java - Joshua Bloch} 

Thursday, December 29, 2011

Creating Java Object -- Part-V


This is a continuation from Creating Java Objects.  The below points that I will be discussing is purely some tips on when to create objects.

Avoid Creating Unnecessary Objects

As the title tells, we should practice to avoid creating unnecessary objects.  Reuse the objects as much as possible.  
·        In order to reuse, if possible use immutable objects. For e.g.
String test = new String("test"); 


Never use the above code because it will tend to create objects each time it is executed. Instead use
String test ="test";

This will reuse the object rather than creating a new one.
·        Use static factory methods to create objects over constructors.  I have discussed the advantages of using static factory methods over constructors.  To iterate the same thing, using Boolean.valueOf(String)will return and existing method whereas Boolean(String) creates new one.
·        Apart of reusing immutable objects we can also reuse mutable objects in some circumstances.  If we know that the objects are not going to be modified then we can reuse it instead of creating it everytime.  For e.g

public class Card {
        public boolean isValid(int fromYear, int toYear) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            cal.set(fromYear, Calendar.JANUARY, 1, 0, 0, 0);
            Date from = cal.getTime();
            cal.set(toYear, Calendar.JANUARY, 1, 0, 0, 0);
            Date to = cal.getTime();
            return from.compareTo(to) >= 0;
        }
}


This isValid() method returns true if the passed dates are proper.  It creates Calendar and timezone objects which are unnecessary here. Instead of this, we could have written

public class Card {
        Calendar cal;
        static {
cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
              }
        public boolean isValid(int fromYear, int toYear) {
            cal.set(fromYear, Calendar.JANUARY, 1, 0, 0, 0);
            Date from = cal.getTime();
            cal.set(toYear, Calendar.JANUARY, 1, 0, 0, 0);
            Date to = cal.getTime();
            return from.compareTo(to) >= 0;
        }
}

This clearly will ensure that the Calendar and Timezone instances are created only once which is at the time of creating the Card class, because static blocks are called exactly once in the life time of an object *.
·        Prefer primitives over wrapper classes. Because internally it will do autoboxing. For e.g

Integer test = 0;

This code will internally autobox to the primitive.


*The static blocks are executed before the constructors.  They are the first in the queue to be called while creation of the object. 

{Courtesy: Effective Java - Joshua Bloch} 

Thursday, December 22, 2011

Creating Java Object -- Part-IV


The Creating of java object continues….


Enforce nonistantiablity with private constructor

Some special classes needs not be instantiated.  For e.g some utility classes like java.util.Arrays, java.util.Collections is not meant for utility methods rather than creating objects.  In order to force noninstantiablity for such classes we can have a private constructor which does nothing or may be just throwing some error.

public class NonInitializingClass {

    public NonInitializingClass() {
        throw new AssertionError();
    }
}
This will guarantee that no instance of this class will be generated.


{Courtesy: Effective Java - Joshua Bloch} 

Creating Java Object -- Part-III


This is the third approach of creating objects:

Singleton Property with private constructor
A singleton is a class which is instantiated only once. Making a class a singleton can make it difficult to test its client, as its impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.  There are few ways of implementing a singleton.
1. By keeping a private constructor and exposing a static final member by one method:
public class SingletonTest {
    public static final SingletonTest OBJECT= new SingletonTest();
   
    private SingletonTest() {
       
    }
   
    public void callMe() {
       
    }
}
The object is initialized only once and called as SingletonTest.OBJECT.  The private constructor will make sure that there no other instance will be created.  

2. One more similar way is to keep a public static factory method in addition to the above arrangement.
public class SingletonTest {
    public static final SingletonTest OBJECT = new SingletonTest();
   
    private SingletonTest() {
       
    }
   
    public static SingletonTest getInstance() {
        return OBJECT;
    }
   
    public void callMe() {
       
    } 
}
Here also the instance gets created only once. Thanks to the private constructor.  As you can see the only difference from the previous approach is the static method (which is in bold). We can call the instance by SingletonTest.getInstance();
The advantage of this approach is it gives a clear idea that the class is singleton.  

{Courtesy: Effective Java - Joshua Bloch} 

Sunday, December 18, 2011

Creating Java Object -- Part-II

Continued from previous post…

The second of way of creating object is as follows:

Builder pattern
This is really an interesting pattern which I have come across lately. Consider a class where there are many fields in which some are quint essential to be initialized and some may not at the time of creating object. In that case we would end up giving n number of constructors in which we may not be knowing which to use and which not to. For e.g 

 public class NutritionFacts {
        private final int servingSize; // required
        private final int servings; // required
        private final int calories; // optional
        private final int fat; // optional
        private final int sodium; // optional
        private final int carbohydrate;

        public NutritionFacts(int servingSize, int servings) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
        }
        public NutritionFacts(int servingSize, int servings, int calories) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
            this.calories = calories;
        }
        public NutritionFacts(int servingSize, int servings, int calories, int fat) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
            this.calories = calories;
            this.fat = fat;
        }
        public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
            this.calories = calories;
            this.fat = fat;
            this.sodium = sodium;
        }

        public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) {
            super();
            this.servingSize = servingSize;
            this.servings = servings;
            this.calories = calories;
            this.fat = fat;
            this.sodium = sodium;
            this.carbohydrate = carbohydrate;
        }
}
 This is called telescoping constructor pattern.  Though this pattern may help in some of the scenarios but it goes out of hand when the parameters go on increasing. Consider creating an object to the above class, you may not be knowing which constructor to call for which case.
An alternate we may think of is JavaBeans pattern. By that we can have only only setters and getters for the parameters and initialize it wherever we need. But by this way we may not be able to handle the creation. As in, a JavaBean may be in an inconsistent state partway through its construction.  One more disadvantage associated to this is that the JavaBeans pattern precludes the possibility of making a class immutable, which in turn would require more effort from the developer to keep it thread safe.

After coming through all this the third alternative that we have is builder pattern.  In this instead of making an object directly, we can call a builder object.  Then the client can set optional parameters if required by calling setters on the builder object. For e.g


public class NutritionFacts {

    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    public static class Builder {
        private int servingSize;
        private int servings;

        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbohydrate = 0;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int val) {
            calories = val;
            return this;
        }

        public Builder fat(int val) {
            fat = val;
            return this;
        }

        public Builder sodium(int val) {
            sodium = val;
            return this;
        }

        public Builder carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }

}
            Now the object can be created as,
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(45).build();
        System.out.println("cocaCola:" + cocaCola.calories);

In order to have builder instead of going and creating it inside the class we can also have Builder interface and just implement it.
Though it has disadvantage of writing builders for each class, but when you see from the perspective of handling this kind of situation then it is worth it I think.  At least better than the telescoping and JavaBeans patterns.

{Courtesy: Effective Java - Joshua Bloch}