design patterns ·
Builder
Separates the construction of a complex object from its representation using a step-by-step builder API.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When constructing an object requires many optional parameters, a constructor with 10 arguments is unreadable. Builder solves this with a fluent API: Pizza.Builder("Large").cheese().pepperoni().build().
A Builder class accumulates parameters via method chaining. The final build() call constructs and returns the immutable product. An optional Director class encapsulates common build sequences.
When to use
HTTP request objects, SQL query builders, configuration objects, test data builders. Any object with 4+ optional parameters.
When not to
Objects with 1-3 parameters - a constructor or static factory is simpler. Mutable objects that need frequent partial updates.
Key insights
- Each setter returns this (or the Builder) to enable method chaining
- build() is the natural place to validate mandatory fields and invariants
- The Director is optional - clients can call builder methods directly
- Builder produces immutable products naturally - all fields set before construction completes