CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Static factory methods

A named method instead of a constructor.

Think of a shop counter. A customer can walk into the back room and build a product by hand, or ask the clerk, "one gift box, please". The clerk's name for the request says what the customer gets.

EJ describes a static factory method as a plain static method whose job is to hand back an object of its own class. Its example is Boolean.valueOf(boolean). EJ also warns that the idea differs from the Factory Method pattern in section 4. The two share a word and little else.

EJ lists several advantages over a public constructor.

  • It has a name. A constructor Money(long) does not say whether the number is rupees or paise. Money.ofRupees(5) and Money.ofPaise(5) do. EJ also warns against two constructors that differ only in the order of parameter types, since nobody can remember which is which.
  • It need not create a new object on each call. It can return a cached instance. Boolean.valueOf never creates an object.
  • It can return any subtype of its return type, so the class returned can stay hidden. The Java Collections framework exposes its utility collections through static methods and keeps their classes non-public. This keeps the API small.
  • The class returned may change with the input. EnumSet returns one of two internal classes depending on the size of the enum.
  • The returned class may not exist yet when the method is written. This is the base of service provider frameworks such as JDBC.

EJ names the downsides too. A class with only private constructors cannot be subclassed, and static factories are harder for a reader to find than constructors in the documentation.

record Money(long paise) {
    static Money ofRupees(long r) { return new Money(r * 100); }
    static Money ofPaise(long p)  { return new Money(p); }
}

Money.ofRupees(5) prints as Money[paise=500] and Money.ofPaise(5) as Money[paise=5]. The names carry the unit.

Static factory method

A static factory method is a static method that returns an instance of its class, usually with a name that says what is being made.

Example: Money.ofRupees(5).

Check yourself: 1. What does EJ say about Boolean.valueOf and new objects? 2. What does Money.ofPaise(5) print? 3. Name two advantages of a name over a constructor.