Effective Java
Item 01

Item 01 Consider static factory methods instead of constructors

Advantages of static factory methods

  • Static factory methods have names
  • Not required to create a new object for each invocation
    • Similar to flyweight pattern
  • Return an object of any subtype of their return type
    • An API can return objects without making their classes public
    • Application: interface-based frameworks (item 20)
  • The class of returned object can vary from call to call as a function of the input parameters
  • The class of returned object need not exist when the class containing the method is written

Limitation of providing only static factory methods

  • Classes without public or protected constructors cannot be subclassed
  • Hard for programmers to find

Common static factory method names

NameDescriptionExample
fromType conversionDate d = Date.from(instant)
ofAggregationSet<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING)
valueOfVerbose alternative to from and ofBigInteger primer = BigInteger.valueOf(Integer.MAX_VALUE)
instance / getInstanceReturn an instance
create / newInstanceReturn a guaranteed new instanceObject newArray = Array.newInstance(classObject, arrayLen)
getTypeReturn an instance of a specific typeFileStore fs = Files.getFileStore(path)
newTypeReturn a new instance of a specific typeBufferedReader br = Files.newBufferedReader(path)
typeConcise alternative to getType and newTypeList<Complaint> litany = Collections.list(legacyLitany)

Service provider framework

A system in which providers implement a service, and the system makes the implementations available to clients, decoupling the clients from the implementation.

ComponentDescriptionJDBC Example
Service interfaceRepresent an implementationConnection
Provider registration APIUsed by provider to register an implementationDriverManager.registerDriver
Service access APIUsed by clients to obtain instances of the serviceDriverManager.getConnection
Service provider interface (optional)Describe a factory object that produces instances of the service interfaceDriver