Design Principle #1: Consider static factory method pattern instead of constructors

In some scenarios, instead of having a constructor, it is better to have a public static factory method that returns an instance of that class. For example, the below method returns an instance of the Boolean object when given boolean primitive type.

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

This method has the following advantages:

  • Unlike static factory methods, they have names
  • It is not necessary to create and return a new object every time. We can return preconstructed/cached instances while using the static factory method.
  • Unlike constructors, they can return an object of any subtype of their return type. See the example below.
public abstract class Shape{
    private static final Shape CIRCLE_INSTANCE = new Circle();
    public static Shape getCircle() {
        return CIRCLE_INSTANCE;
    }
    public abstract void draw();
}

class Circle extends Shape{
    @Override
    public void draw(){
        System.out.println("Drawing Circle");
    }
}

 

The main limitation of providing static factory methods is that classes without public or protected constructors cannot be subclassed. Also, sometimes factory methods are hard for the programmers to find since they do not stand out in the API documentation in the way constructors do. Still, I believe there are more reasons to use the static factory method and it should be part of every programmer’s toolkit.

References: Effective Java by Joshua Bloch

 

2 thoughts on “Design Principle #1: Consider static factory method pattern instead of constructors

Leave a comment