liveBook · Manning

Builder pattern

As explained in The Art of Code

The builder pattern separates the construction of a complex object from its representation through a dedicated stepwise construction interface.

The builder pattern makes complex object creation readable by replacing long, position-sensitive constructors with a dedicated, stepwise construction interface. It is especially useful when many fields are optional: each named operation communicates what value is being supplied, rather than leaving readers to interpret nulls or argument positions. section 4.1.2

Person p = new Person("John", "Doe", 
  null, null, 38000, "France", 25, 0, 50, 50);

A long constructor hides intent: nulls are ambiguous, and positional values can be placed in the wrong fields. section 4.1.2

Person p = Person.builder().firstname("John")
                 .lastname("Doe")
                 .town("Grenoble")
                 .build();

The builder turns construction into a readable sequence of named choices and includes only the parts the object needs. section 4.1.2

The alternative is constructor overloading, but telescoping constructors become unmanageable as optional fields multiply. A manually implemented builder is also verbose, so the gain is clearest when construction complexity makes argument ordering and intent difficult to verify. section 4.1.2

How The Art of Code covers it

How deep it goes
Explains the construction problem and usage pattern, but stops short of showing the builder implementation.
Examples
Uses a ten-field Person constructor with nulls, telescoping Person constructors, and a named Person builder chain.
What it assumes
Assumes familiarity with object instantiation, constructors, optional parameters, and encapsulation.
What you can do after
Evaluate when named, stepwise construction reduces ambiguity more effectively than overloaded constructors.
How it connects
Connects object construction with encapsulation, constructors, telescoping constructors, and data modeling.

Also explained in

Compare how 6 books explain builder pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.