Item 01 - Consider static factory methods instead of constructors

From Effective Java 2/e by Joshua Bloch

Advantages

  1. Meaningful name for each constructor
    BigInteger.probablePrime()
    
  2. No need to create object every time if it's unnecessary
    • Choose to use cached object or create a new one
  3. Possible to return subclass object
  4. Easy to create parameterized type object

    public static <K, V> HashMap<K, V> newInstance() {
      return new HashMap<K, V>();
    }
    
    
    Map<String, List<String>> m = HashMap.newInstance();
    

Disadvantages

  1. Impossible to make subclass if a class is consist of static factory method without any public or protected constructor
  2. Hard to distinguish between static factory method and static method

Naming Convention

valueOf()
of()
getInstance()
newInstance()
getType()
newType()

Consider to make static factory method for each class because it has lots of advantages.

Posted by The Finest Artist