Consider static factory methods instead of constructors

Event though a constructor is a fairly standard and natural way of creating instances of a class, there are other ways to do it. And they might be sometimes better suited to do the job that needs to be done.

You ill find this pattern in many libraries API, just think of Integer.valueOf() or getInstance(). All this comes in handy, when we want to have more control over how the object is created, if it is created at all and what type of object is in fact instantiated. Plus, we do get a bonus of meaningful naming.

Let’s consider an example of static factory method

public class Color {
    private static Color BLACK = new Color(0);
    
    public static Color fromRgb(String rgbStr) {
        return new Color(getRgbIntFromRgbStr(rgbStr));
    }

    public static Color fromCmyk(String cmykStr) {
        return new Color(getRgbIntFromCmykStr(cmykStr));
    }

    public static Color black() {
        return BLACK;
    }
    (...)
}

Why could you use static factory method instead of constructor

  1. Factory method can have a meaningful name
  2. Factory method can “reuse” objects, it doesn’t need to create a new one every time
  3. Factory method can return an object of different subtypes
  4. Factory method can return different implementation (class), based on input parameters

What are the drawbacks of using static factory methods instead of constructors

  1. Classes without accessible constructors cannot be subclassed
  2. Factory methods are not as obvious to find in object’s API as a constructor

https://londonist.com/2013/07/battersea-power-station-chimneys-could-be-demolished

This post is based on item Consider static factory methods instead of constructor from Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)