Builder
medium 50 minThe 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
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
1994
The book Design Patterns lists Builder among its creational patterns, with a converter of text documents as its example.
2005
Martin Fowler describes the fluent interface on 20 December, a name found together with Eric Evans.
2008
The second edition of Effective Java by Joshua Bloch recommends a nested builder when a constructor would have many parameters.
2011
Java 7 adds Locale.Builder, which checks each part and can be cleared and used again.
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.
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.
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.
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);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)Why overloads do not scale
The design that hurts
1/3Constructors pile up
Four constructors and a setter. Each new part adds one more, and the parts are public and changeable.
uses
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
nullfor 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
1/4The steps
An interface with one method per decision. Each returns the builder, so calls can be chained.
useshas (lives on)implementsdepends on
The life of a builder
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.
// 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)); }}What each call returns
build. Only there the type changes.Names tell what a step does
| Name | Meaning | Called twice |
|---|---|---|
setBun(x) or bun(x) | One value | The last one wins |
addTopping(x) | Collects | Both stay, in order |
toasted() | Switches something on | No change |
withEmail(x) | Often: a changed copy, or a test builder | Ask. with is also used for new objects |
reset() or clear() | Back to the defaults | No change |
build() | Check and create | A second product, or an error. Decide |
toppings(list) adds in one class and replaces in another, callers will guess.The border
What build() has to do
- 1
Check required parts
No bun, no burger. Say which part is missing.
- 2
Check rules between parts
A GET has no body here. A timeout is positive. No single setter can see such rules.
- 3
Copy what can change
Lists and maps are copied, or the builder and the product share them.
- 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
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.
methodbeforebodyfails, 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?
// 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());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?
Where it appears
| Object | Parts | Why a builder |
|---|---|---|
| HTTP request | Method, address, headers, body, timeout, retries | Optional parts, rules between them |
| SQL query | Table, columns, conditions, joins, order, limit, offset | Parts come from different places |
| String | Pieces | Creating a new string for each piece is slow |
| Subject, body, recipients, attachments | Collects lists | |
| Dialog | Title, message, icon, buttons, callbacks | Nearly everything is optional |
| Document | Headers, paragraphs, tables, images, pages | Same steps, PDF or HTML |
| Game character | Class, weapon, skills, look | Presets |
| Car, house, meal | Engine, rooms, toppings | Configuration with rules |
| Test data | A user, an order | Defaults, and one value that matters |
| Configuration | Connections, security, feature switches | Checked once at the start |
Neighbours
| Builder | Factory method | Abstract factory | Prototype | |
|---|---|---|---|---|
| Creates | Step by step | In one call | In one call per kind | By copying |
| Question | How is it put together? | Which class? | Which matching set? | Like which example? |
| Best for | Many optional parts | One product, several variants | Families | Objects that are costly to set up |
| Product | Usually immutable | Any | Any | A 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
- Design Patterns (publisher's page)
- Martin Fowler: FluentInterface
- Java: HttpRequest.Builder
- OkHttp: Request source
- Project Lombok: @Builder
- Protocol Buffers: Java generated code
- Java: Stream.Builder
- Java: Locale.Builder
- Guava: ImmutableList.Builder
- Rust API Guidelines: builders
- jOOQ: the SELECT statement
- Python: dataclasses