Card 09/ 09

RecapDifficulty: Advanced1 min

Recap: Builder Pattern

Assemble an object one part at a time and validate once, where named arguments are not enough.

Builder moves the construction of a complex object into a builder that sets one part per call and validates the whole in build().

  • Intent. Separate the construction of a complex object from its representation, so the same construction process can create different representations.
  • Participants. The builder declares a step per part and build(); the concrete builder stores the parts and creates the product; the optional director runs fixed sequences of steps.
  • Recognise it by shape. Calls that each set one named part, often chained, then one final call that returns the finished object.
  • In the wild. HttpRequest.newBuilder() in Java 11 and later sets the URI, headers, timeout and method, and build() returns an immutable request.
  • In Python. Keyword arguments with defaults and a frozen dataclass replace a builder whenever every part is known at the call.
  • When it pays. Many optional parts, an object assembled across statements, or parts that accumulate. A short constructor whose arguments are already clear does not need one.