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.
3 points to say:
- Static factory: meaningful name, return a cached object, return a hidden subtype.
- Builder: immutable objects, validation in
build(); avoids telescoping constructors and JavaBeans setters (half-built objects). - 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.