Showing posts with label objects. Show all posts
Showing posts with label objects. Show all posts

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 15, 2011

Creating Java Objects

To give a background of this post, this post speaks about the best practices for creating an object.  There are so many ways of creating an object, but what interests here is which is the best way.  As it is a long list, I will not like to pile up everything here.  So I will keep posting all of them one by one in post after post.  I hope you will find it helpful.

Creating Objects By Static methods(Static Factory):

We know that constructors are the normal way of creating an instance of a class. But using static methods has its own advantages and disadvantages.  We can use it as per our requirements. 
Advantages:
  • The first advantage of using a static method is static methods have name but constructors doesn't have. For example if we call new BigInteger(int, int, Random), which will probably return a prime number.  Instead of this we can call a static method which will have a name like BigInteger.probablePrime, by which the user will come to know that this method can be called when a prime number is expected to be created.
  • The second advantage is static methods are not required to create a new object each time they are invoked.  This is helpful when immutable class's objects are created.  It will allow the immutable class to cache the object or to use a preconstructed instance and use them repeatedly. For e.g. Boolean.valueOf(boolean) returns an object, but it never creates an object. The classes that do this are said to be instance-controlled.  But now the question is where we can use this in our implementation. We can use this where we need to have strict control over creation of objects. Now the next question which comes to our mind is why we should use this instance control. The answer to this is,
·         This guarantees that a class is singleton or non-instantiable
·         Allows an immutable class to make the guarantee that no two equal instances exist, by which the client will be assured to use == operator instead of equals()
  • The third advantage is static methods can return object of any subtype of their return type. That means any class that is a subtype of the declared return type is permissible.
  • The fourth advantage is static factory methods is that they reduce the verbosity of creating parameterized type instance.  For example while creating an object through constructor; we need to provide type parameters even if it is obvious.
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
This is really redundant and painful. The same thing we can achieve by the following snippet into HashMap class :
public static <K, V> HashMap<K, V> newInstance() {
return new HashMap<K, V>();
}
And the calling this as following:
Map<Integer, List<Integer>> map = HashMap.newInstance();
This is quite intelligent, isn’t it??
Let’s have a look at the disadvantages of having static factory.
Disadvantages:
  • The main disadvantage is if only static factory methods is provided to class which doesn’t have any public or protected constructors, then it cannot be further subclassed.  That means it will be impossible to create a subclass if there is no public or protected constructor is there in a class.  For example if the same would have been implemented in a Collection class, we could not have subclassed it.
  • A second disadvantage may be static factory methods are not readily distinguishable from other static methods.  That speaks about they cannot be treated specially in the API doc so that the client would identify it as a static factory method. 
{Courtesy: Effective Java - Joshua Bloch}