11/3/11

Good Practices : Programming Tips Java

One of the Good practices while programming using Java is listed below.


Consider Static Factory Methods instead of Constructors

The normal way for a client to obtain an instance of itself is to provide a public constructor. But apart from this their is another technique which should be the part of every programmer's toolkit. A class can provide a static factory method, which is static method which returns the instance of the class.


Example :

The below method translates a boolean primitive value into Boolean object reference.


public static Boolean valueOf(boolean b){
    return b ? Boolean.TRUE : Boolean.FALSE;
}

Note : 


A class can have static factory method instead of, or in addition to, constructors.

Advantages of using static factory methods :

1. Unlike Constructors, static factory methods have names :


If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well chosen name is easier to use and the resulting client code easier to read. For example, the constructor BigInteger(int, int, Random), which returns a BigInteger that is probably prime, would have been better expressed as a static factory method named  BigInteger.probablePrime.


2. Static factory method do not require to create a new object each time they are invoked :


This allows immutable classes to use preconstructed instances, or to cahce instances as they are constructed as to avoid creating unnecessary duplicate objects. The Boolen.valueOf(boolean) method illustrates this technique; it never creates an object. This can greatly improve performance.


3. Static factory methods can return an object of any subtype of their return type :

This gives us the flexibility of choosing the class of the returned object. To understand the above advantage better lets take an example :



The class java.util.EnumSet introduced in 1.5 release, has no public constructor, but only static factories. They return one of the two implementations depending upon the size of the underlying enum type; if it has 64 or fewer elements, the static factories return RegularEnumSet instance, which is backed by single long; if enum type had 64 or more elements, the factories return JumboEnumSet instance, backed by a long array.

The existence of the two implementations are invisible to the client. So a future release could add third or fourth implementation with a different returned value. 



4. Static factory methods reduce the verbosity of creating the parameterized type instances :


Unfortunately, we must specify the the type parameters when we invoke the constructor of a parameterized class even if they are obvious from context. This makes us provide the type parameters twice in quick succession :


Example : 


Map<String, List<String>> m= new HashMap<String, List<String>>


This redundant specification quickly becomes painful as the length and complexity of the type parameter increase. But with static factories, the compiler can figure out the type parameters for us. This is called type inference. For example,


public static <K, V> HashMap<K, V> newInstance(){
           return new HashMap<K, V>();
}


The above statement can reduce the verbosity :


Map<String, List<String>> m=HashMap.newInstance();
@courtesy Effective Java.

SHARE THIS POST:

Related Posts:

  • Karel -the Robot learns Java using Eclipse Tutorial Karel The Robot is a robot simulator that affords a gentle introduction to computer programming. Users write Karel programs and feed them to the simulator to watch them execute. By solving karel problems you will build you… Read More
  • RGB Color Chooser Applet Java Code A RGB Color Chooser shows three sliders that the user can manipulate to set the red, green, and blue, components of a color. A color box shows the selected color, and there are three labels that show the numerical values of… Read More
  • Merge Sort using Java with program code In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists (or any such linear sequential data storage structure) into a specified order. It is a particularly good example of the divide and co… Read More
  • Microsoft SQL Server 2008 connection using ODBC tutorial My previous post was on SQL Server installation . Now today I will be telling how to connect your database ie SQL Server using ODBC with Netbeans. After you installed SQL Server 2008 Express successfully, now its time to … Read More
  • Java Tutorial : Identifiers, Keywords and Types Identifiers : In Java programming language, an identifier is a name given to a variable, class or method. Identifiers start with a letter, underscore(_) or dollar sign ($). The following characters can be digits. Identifi… Read More