Monday, July 14, 2014

What are static factory methods in java

In java we often have to deal with creating and destroying the objects. Public constructors have been widely used for creating an instance of the class. But for writing programs that are clear, correct, usable, robust, flexible and maintainable static factory method is another technique that every java programmer should know.
Having static factory method does not mean eliminating the constructor. A programmer can use static factory method in addition to public constructors.

Advantages of static factory method

  • Static factory methods have well chosen names.
A static factory method with a name is comfortable for use compared to many public constructors that have variable parameters. If such multiple constructors exist in class then we may end up calling a wrong one by mistake so static factory method eliminates this restriction.
For example, myClass(int a, int b, int c) constructor returns date, month and year then instead of that we could have a static factory method as myClass.retriveDate().

  • Static factory methods improves performance.
If equivalent objects are requested often to the class then a pubic constructor produces a new duplicate object on every request. Static factory methods comes over this drawback. It relieves immutable class from creating unnecessary objects.
It improves performance if repeatedly object creation requests are expensive. So in this way static factory method open up a way for instance-controlled classes (classes that maintain control over what instance exist at any time).


  • Unlike Constructors static factory method returns an object any subtype of their return type.
This flexibility allows classes to return objects without being public. So in this way it hides implementation.

  • Another Advantage is that they decrease the verbosity of creating parameterized type constructors.
 For example, following declaration requires you to provide type parameters two times in quick succession.
Map<String, List<String>> m = new HashMap<String, List<String>>();

 Now using static factory methods we can deploy it easily as follows
 private static <K, V> HashMap<K, V> newInstance()
{
            return new HashMap<K, V>();
}
and u can replace above declaration in a compact way like this
Map<String, List<String>> m = HashMap.newInstance();

Disadvantages of  static factory methods

  • Classes without public or protected constructors cannot be subclassed.
  • Static factory methods are easily distinguishable from other static factory methods.
     In order to overcome this disadvantage you should adhere to some common and unique static factory method naming. For instance, valueOf(), of(), getInstance(), newInstane(), getType(), newType().

No comments:

Post a Comment