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} 

No comments:

Post a Comment