SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 17 / 42

Middle

When do you use a static factory method or a Builder instead of a constructor?

Short answer

A static factory method (Money.of(...), List.of(...)) replaces a constructor when you want a meaningful name, to return an existing object or a hidden subtype. Use a Builder when there are many parameters, especially optional ones.

YesNoYesNoNeed an objectMany optionalparameters?Builder, validate in buildNeed a name, cache,hidden subtype?Static factoryConstructor

3 points to say:

  1. Static factory: meaningful name, return a cached object, return a hidden subtype.
  2. Builder: immutable objects, validation in build(); avoids telescoping constructors and JavaBeans setters (half-built objects).
  3. Don't pool lightweight objects yourself; pool only expensive resources.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.