AlgoViz

Builder

medium 50 min

The Builder collects the parts of a complex object one by one, checks them together, and creates the object in a single moment.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:31

Builder

1:02Reel

Theory

Read or listen first. About 2 min.

What it is

The Builder is a creational design pattern. A separate object receives the parts of a product step by step. When all is there, build() creates the product.

In the classic form the steps are an interface. A director calls them, and different builders make different representations from the same calls. In the fluent form there is one product, the steps return the builder so that they can be chained, and the product is immutable.

Both forms split a life in two: a changeable phase that nobody else sees, and a finished object.

Why it exists

Constructors with many parameters are read by position. Two values of the same type can be swapped and nobody notices. Overloads for optional parts multiply.

Setters make calls readable, but the object exists before it is complete and stays changeable for ever. Rules between parts have no moment at which they could be checked.

A builder gives names to the values, a moment to the checks, and lets the product be immutable.

A short history

  1. 1994

    The book Design Patterns lists Builder among its creational patterns, with a converter of text documents as its example.

  2. 2005

    Martin Fowler describes the fluent interface on 20 December, a name found together with Eric Evans.

  3. 2008

    The second edition of Effective Java by Joshua Bloch recommends a nested builder when a constructor would have many parameters.

  4. 2011

    Java 7 adds Locale.Builder, which checks each part and can be cleared and used again.

  5. 2013

    Lombok 0.12.0 introduces @Builder, first as an experimental feature.

Words to know

Product
The object that is built.
Builder
The object that collects the parts and creates the product.
Director
An optional object that knows sequences of steps.
Fluent interface
Methods that return an object to continue with, so that calls read like a sentence.
Telescoping constructor
A series of overloads, each with one more parameter.
Staged builder
A builder whose steps return different types, so that required parts are enforced by the compiler.
One shot
A builder that can be used for one product only.
Defensive copy
A copy of a list or map, so that two objects do not share it.
toBuilder
A new builder filled with the values of a product.
Test data builder
A builder in tests with harmless defaults for everything.
Self type
A type parameter that tells a base builder the type of its subclass.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Collect. One named step per decision

Understand it

Start here

Collect first, create once

Some objects need many decisions. A request has a method, an address, headers, a body, a timeout. Most of them are optional, some depend on each other, and the finished object should never change. The builder is a helper that collects the decisions one by one, checks them together, and creates the object in a single moment.

A kite, spar by spar
"Tall, red, yes, no, yes, 3, yes!"?

The bench may be messy. The kite that leaves it is complete, tested and fixed.

Two things carry this name, and interviewers mean either. The classic builder has an interface of steps and several builders that make different things from them. The fluent builder is a small class beside one immutable product, with chained methods and a build() at the end. You will write the second one far more often.

The parts

  • Product

    The complex object: Burger, HttpRequest, Car. Best immutable.

  • Builder

    The steps, and build(). In the classic form an interface: CarBuilder, ReportBuilder.

  • Concrete builder

    Remembers the decisions and creates one kind of product: HtmlReportBuilder, PizzaBuilder.

  • Director

    Optional. Knows useful sequences of steps: CarDirector, BurgerDirector.

  • Client

    Calls the steps itself, or hands a builder to a director.

Why

The telescoping constructor

A class starts with two parameters. Then one more, with a default. Then five overloads, each calling the next longer one, like a telescope. The definition is ugly. The calls are dangerous.

Java
class Pizza {    Pizza(String size) { this(size, "Regular"); }    Pizza(String size, String crust) { this(size, crust, false); }    Pizza(String size, String crust, boolean cheese) { this(size, crust, cheese, false); }    Pizza(String size, String crust, boolean cheese, boolean pepperoni) {        this(size, crust, cheese, pepperoni, false);    }    Pizza(String size, String crust, boolean cheese, boolean pepperoni, boolean mushrooms) { /* ... */ }}Pizza p = new Pizza("Large", "Thin", true, false, true);
What do the booleans mean? The compiler does not know either.
Python
class Request:    def __init__(self, url, method, body, timeout, retries):        self.url, self.method, self.body = url, method, body        self.timeout, self.retries = timeout, retriesr = Request("https://api.example.com/pay", "POST", "{}", 3, 30)   # meant: 30 s, 3 triesprint("timeout", r.timeout, "s, retries", r.retries)class SetLater:    passs = SetLater()                  # the other extreme: create empty, fill laters.method = "POST"s.timeout = 30try:    print(s.method, s.url)      # forgotten, and found far away from hereexcept AttributeError as e:    print("too late:", e)
Run it. Two swapped numbers, no error, and a request that gives up after three seconds and tries thirty times.
Edit and run it in your browser

Why overloads do not scale

n optional parts⇒2n combinations210=1024n \text{ optional parts} \Rightarrow 2^n \text{ combinations} \qquad 2^{10} = 1024
Ten optional parts make 1024 possible burgers. Constructors can not name them, and two overloads with the same types can not even exist side by side. A builder needs ten methods.

The design that hurts

Burger+ bun: String+ patty: String+ cheese: String+ toppings: List+ toasted: bool+ Burger(bun)+ Burger(bun, patty)+ Burger(bun, patty, cheese)+ Burger(5 parameters)+ setCheese(c)

1/3Constructors pile up

Four constructors and a setter. Each new part adds one more, and the parts are public and changeable.

uses

Two smells: long lists of parameters of the same type, and objects that are complete only after a few more calls.

Builder

  • Each value has a name
  • Leave out what you do not need
  • The product exists only when complete
  • All rules are checked in build()

Long constructor or setters

  • Positions instead of names
  • null for everything you do not need
  • Half-built objects can be seen by others
  • Rules between fields have no place

The idea

Two lives: a changeable one and a fixed one

Split the object in two. The builder is changeable, short-lived and used by one thread. The product is fixed, long-lived and can be shared. build() is the border.

The builder in general

Client+ order()«interface»Builder+ setBun(b): Builder+ setPatty(p): Builder+ build(): Product

1/4The steps

An interface with one method per decision. Each returns the builder, so calls can be chained.

useshas (lives on)implementsdepends on

Without several builders you drop the interface, and without repeated recipes you drop the director. Two classes remain.

The life of a builder

Decide whether a builder may be used again after build(), and write it down. Both answers exist in real libraries.

The chain

Fluent interfaces

A step that returns the builder can be followed by the next step. Eric Evans and Martin Fowler named this style fluent interface in 2005. Chaining alone is not a builder: a stream pipeline chains too.

Java
// without a chainPizzaBuilder builder = new PizzaBuilder();builder.setSize("Large");builder.addTopping("Pepperoni");builder.addTopping("Cheese");builder.setCrust("Thin");Pizza pizza = builder.build();// with a chainPizza same = new PizzaBuilder()    .setSize("Large")    .addTopping("Pepperoni")    .addTopping("Cheese")    .setCrust("Thin")    .build();class PizzaBuilder {    private String size = "Medium";    private String crust = "Regular";    private final List<String> toppings = new ArrayList<>();    PizzaBuilder setSize(String size) { this.size = size; return this; }      // the whole trick    PizzaBuilder setCrust(String crust) { this.crust = crust; return this; }    PizzaBuilder addTopping(String t) { toppings.add(t); return this; }    Pizza build() { return new Pizza(size, crust, List.copyOf(toppings)); }}
Six statements and a temporary name, or one expression.

What each call returns

The same object is handed along until build. Only there the type changes.

Names tell what a step does

NameMeaningCalled twice
setBun(x) or bun(x)One valueThe last one wins
addTopping(x)CollectsBoth stay, in order
toasted()Switches something onNo change
withEmail(x)Often: a changed copy, or a test builderAsk. with is also used for new objects
reset() or clear()Back to the defaultsNo change
build()Check and createA second product, or an error. Decide
Mixing meanings is a common bug: if toppings(list) adds in one class and replaces in another, callers will guess.

The border

What build() has to do

  1. 1

    Check required parts

    No bun, no burger. Say which part is missing.

  2. 2

    Check rules between parts

    A GET has no body here. A timeout is positive. No single setter can see such rules.

  3. 3

    Copy what can change

    Lists and maps are copied, or the builder and the product share them.

  4. 4

    Create in one moment

    The constructor gets everything. It is private or package-private, so nobody goes around the checks.

One order, from empty to fixed

Toppings may be left out or come in another order. reset matters only when the builder was used before.

Where should the rule "a POST needs a body" be checked?

BreaksIn the setters
How
method("POST") raises if there is no body yet.
Limit
Now the order of the calls matters. method before body fails, although the result would be fine.
Choose when
Only for rules about one value alone, such as a negative timeout.
WorksIn build()
How
All parts are known, so the rule can be checked once.
Limit
Whoever calls the constructor directly goes around it.
Choose when
The constructor is private.
StrongIn the product's constructor, called by build()
How
The product defends itself. build() adds the checks about completeness and collects messages.
Limit
Two places: know which rule belongs where.
Choose when
The product can also be made in other ways: parsing, copying, tests.

Recipes

Do you need a director?

Java
// without: the client knows all the stepsCar car = new CarBuilder()    .setEngine("V8 500HP").setSeats(2).setTransmission("6-Speed Manual")    .setGps("Racing GPS").setColor("Racing Red").build();// with: the recipe has a namefinal class CarDirector {    Car buildSportsCar(CarBuilder builder) {        return builder.setEngine("V8 500HP").setSeats(2)            .setTransmission("6-Speed Manual").setColor("Racing Red").build();    }    Car buildFamilyCar(CarBuilder builder) {        return builder.setEngine("V6 250HP").setSeats(5)            .setTransmission("Automatic").setAirBags(true).build();    }}Car sports = new CarDirector().buildSportsCar(new CarBuilder());
Without a director every client knows the recipe. With one, the recipe has a name.

Use a director when

  • The same configuration is needed in several places
  • The order of the steps is knowledge worth hiding
  • There are several presets
  • Several builders follow the same steps

Skip it when

  • Every build is different
  • There is only one recipe
  • The client has to know the steps anyway
  • A function with a good name would do the same

Choosing

When to use it and when not

Use it when

  • Many optional parts
  • The product must be immutable and valid
  • Parts arrive one by one, for example from a parser
  • The same steps make different products
  • Rules connect several parts
  • The call should read like a sentence

Leave it when

  • Few fields, or all of them required
  • The language has named arguments with defaults, and nothing more is needed
  • The object is changeable anyway
  • It is created in a hot inner loop
  • The builder would only repeat the fields

Which tool creates this object?

Python, Kotlin, C# and TypeScript often stop at F. Java and C++ usually arrive at G.

Where it appears

ObjectPartsWhy a builder
HTTP requestMethod, address, headers, body, timeout, retriesOptional parts, rules between them
SQL queryTable, columns, conditions, joins, order, limit, offsetParts come from different places
StringPiecesCreating a new string for each piece is slow
EmailSubject, body, recipients, attachmentsCollects lists
DialogTitle, message, icon, buttons, callbacksNearly everything is optional
DocumentHeaders, paragraphs, tables, images, pagesSame steps, PDF or HTML
Game characterClass, weapon, skills, lookPresets
Car, house, mealEngine, rooms, toppingsConfiguration with rules
Test dataA user, an orderDefaults, and one value that matters
ConfigurationConnections, security, feature switchesChecked once at the start

Neighbours

BuilderFactory methodAbstract factoryPrototype
CreatesStep by stepIn one callIn one call per kindBy copying
QuestionHow is it put together?Which class?Which matching set?Like which example?
Best forMany optional partsOne product, several variantsFamiliesObjects that are costly to set up
ProductUsually immutableAnyAnyA copy of the example

What you gain, what you pay

  • Readable calls

    Names instead of positions.

  • Immutable products

    Created complete, safe to share. See Immutability.

  • One place for rules

    Checked when all parts are known.

  • More code

    Each field appears in the product and in the builder. Generators help.

  • Errors move to run time

    A forgotten part is found by build(), not by the compiler. Staged builders bring it back.

  • One more object

    Short-lived and cheap, but not free in a hot loop.

Summary

The whole topic in one minute.

Collect named decisions in a changeable builder, check them together, create an immutable product once. Steps return the builder, build returns the product.

Form of one value: in the step. Rules between parts: in build and the constructor. Facts about the world: in the service. Report all problems at once.

Copy lists, say whether a builder can be reused, share products and never builders. Use stages when the compiler should ask for required parts, and no builder at all when named arguments do the job.

  • A builder collects named decisions and creates the product once, complete and checked.
  • The builder is changeable and short-lived. The product is immutable and can be shared.
  • Each step returns the builder. Only build() returns the product.
  • Rules between parts belong into build() or the product's constructor, never into the order of the setters.
  • Copy lists and maps in build().
  • A director is optional: named recipes over the same steps.
  • With named arguments and few rules, a constructor is enough.

Sources