Effective Java : Item 1

Consider Static Factory Methods instead of Constructors

A method that returns an instance of the class. A class can provide its clients with a static factory method instead of or in addition to constructors.

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

Notes

java.util.EnumSet has no public constructors. Only static factories. It returns one of two implementations based on the size of the underlying Enum Type. If the size is smaller than 64, the factory returns a RegularEnumSet else it returns a JumboEnumSet that is backed by a long array. The existence of these 2 classes is hidden from the client. If RegularEnumSet ceased to offer the performance benefits, it can be dropped with no ill effects. Clients don't care what they get back from the factory, they only care that it is a sub type of EnumSet.

Advantages

  • Unlike constructors static factory methods can have names. A static factory with a well chosen name is easier to use and read.
  • Avoid having multiple constructors that differ only in the order of parameter types.
  • Unlike constructors they are not required to create a new object each time it is invoked. Strategies like caching or pre constructed instances can be used.
  • Unlike constructors a SFM can return an object of any subtype of the return type adding to flexibility.
  • Class of the object returned by the SFM need not even exist at the time of writing of the method.
  • SFM reduces the verbosity of creating parametrized type instances.

Disadvantages

  • The main disadvantage of providing only SFM is that classes without public or protected constructors cannot be sub classed.
  • They do not stand out from other static static methods.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License