Builder separates how an object is put together from the object itself. Instead of one constructor call with a long list of positional arguments, the caller configures a separate builder object one named step at a time and then asks it to build() the finished product, which can check the whole configuration first and hand back an immutable result. The Gang of Four version adds a director that runs a fixed sequence of steps against any builder, so the same recipe can produce different representations. Both forms are everywhere in modern libraries, from StringBuilder to HTTP clients.
Think of it like
Ordering at a sandwich counter
You do not shout "large, true, false, true, null, 2" at the person behind the counter. You say "a large one", then "cheese", then "basil", then "no olives, thanks", and only when you say "that's it" do they wrap the sandwich. If you forget to choose the bread, they ask before making anything. The counter conversation is the builder, "that's it" is build(), and the wrapped sandwich is the product. A franchise recipe card that any counter can follow is the director.
The problem
A pizzeria app models an order as a Pizza with a size and three toppings. The first version gives Pizza one constructor, with defaults for the optional toppings. This is the Before version of the Fluent scenario in the visualizer above.
class Pizza {
constructor(
readonly size: string,
readonly cheese = false,
readonly olives = false,
readonly basil = false,
) {}
}
const large = new Pizza("large", true); // cheese, the reader must know
// The order: small, cheese, basil, no olives.
const small = new Pizza("small", false, true, true); // oopsThe second call is wrong. To reach basil, the fourth parameter, the caller has to write every boolean before it, and two of them went in the wrong order. Both are boolean, so it compiles, runs and bakes a pizza with olives and no cheese. In the visualizer the small object shows cheese = false, olives = true, and the kitchen returns "baked small: olives, basil" without any error.
- Call sites are unreadable.
new Pizza("small", false, true, true)says nothing about what each value means. Real classes reach six to ten parameters (new Pizza("large", true, false, true, null, 2)), and IDE hints do not help in code review. - Same-typed parameters swap silently. The type checker cannot tell
cheesefromolives. The mistake only shows when someone looks at the result. - Optional values come in a fixed order. To set the last option you must also spell all the earlier ones. In languages without default parameters (Java, C#) this turns into the telescoping constructor: one overload for each prefix of the parameter list.
- Validation is awkward. A constructor can check its arguments, but the usual escape from long constructors, an empty object plus setters (the JavaBeans pattern), leaves the object half-built and invalid between the setter calls, and it can no longer be immutable.
The pattern
Intent (from the Gang of Four book): separate the construction of a complex object from its representation, so that the same construction process can create different representations. In everyday code the word means a slightly different thing, the fluent builder popularized by Effective Java (Item 2: "consider a builder when faced with many constructor parameters"). This lesson covers both, and the visualizer has one scenario for each.
- Product (
Pizza) - The complex object being built. With a fluent builder it is usually immutable and has no public way to be built half-finished.
- Builder (
PizzaBuilder) - Collects the configuration step by step in its own mutable fields, with a default for everything optional. Each step is a named method.
build()- The final step. It validates the collected values as a whole and only then creates the product, in one go. Invalid input means an exception and no product.
- Director (
Chef, GoF form only) - Knows a construction recipe as a sequence of steps and runs it against the abstract builder interface. It does not know what is being built.
- Abstract builder (
Builder, GoF form only) - The interface of the steps. Each concrete builder implements them to produce its own representation, and offers its own method to get the result.
The fluent builder
class PizzaBuilder {
private size?: string;
private cheese = false; // defaults live in the builder
private olives = false;
private basil = false;
withSize(s: string): this {
this.size = s;
return this; // returning the builder makes the calls chain
}
addCheese(): this {
this.cheese = true;
return this;
}
// addOlives() and addBasil() look the same
build(): Pizza {
if (!this.size) throw new Error("no size"); // check the whole order
return new Pizza(this.size, this.cheese, this.olives, this.basil);
}
}
const pizza = new PizzaBuilder()
.withSize("small")
.addCheese()
.addBasil()
.build(); // small: cheese, basilEvery option now has a name at the call site, options the caller does not want are simply not called, and the order of the calls does not matter. The product is created once, at the end, from values build() has already checked, so no code ever sees a pizza without a size. The builder is the only mutable part, and it is thrown away after build().
The GoF form: director and builders
interface Builder {
setSize(s: string): void;
addCheese(): void;
addBasil(): void;
}
class Chef { // the director
margherita(b: Builder): void {
b.setSize("large");
b.addCheese();
b.addBasil();
}
}
const chef = new Chef();
const builder = new PizzaBuilder(); // implements Builder
chef.margherita(builder);
const pizza = builder.getPizza(); // a Pizza object
const bill = new BillBuilder(); // implements Builder
chef.margherita(bill);
const price = bill.getTotal(); // 13: the same steps, pricedHere the steps return nothing and there is no chaining. The point is different: the recipe is written once in the director, and each concrete builder decides what a step means. PizzaBuilder.addCheese() sets a flag on the future pizza; BillBuilder.addCheese() adds 2 to a total. The two results have nothing in common, so there is no shared getResult() in the interface: the client created the concrete builder and asks it directly. The GoF book's own example is an RTF reader (the director) that drives converters producing plain ASCII text, TeX, or an editable text widget from the same document.
What the visualizer shows
- Fluent, Before: a
Pizzawith a four-parameter constructor and aKitchen. The run createslargefromnew Pizza("large", true), thensmallwith the swapped booleans; the Objects view showscheese = false,olives = trueonsmall, andbake(small)returns"baked small: olives, basil". - Fluent, With Builder: each chained step is a call from the client to
builder, a field write (builder.cheesebecomestrue), and a return ofbuilderitself, so the sequence view shows the same lifeline receiving every call.build()checks the size, then the «create» arrow fromPizzaBuildertoPizzalights andpizzaappears with the right values. A second builder,builder2, is never given a size: itsbuild()throwsno sizeback to the client, and no second pizza appears. - Director: the client hands
buildertochef.Chef.margherita()calls three steps; each call lights theBuilderinterface in violet (it declares the step) andPizzaBuilderin amber (its code runs). The client then callsgetPizza()itself. - Change requests: Add crust (Fluent) and Add bill (Director) apply to whichever version is shown. Touched classes get a badge, and the Change request panel beside the code counts what each version changed.
Pick Fluent or Director in the toolbar, then press Play or step with the arrow keys: the engine really runs the classes in the code panel. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Start a builder
With Fluent and With Builder selected, the client creates
builder. Its constructor sets the defaults:cheese,olivesandbasilarefalse, andsizeis still empty. - 2
Set the size
builder.withSize("small")writesbuilder.sizeand returnsbuilderitself. That return value is what the next.addCheese()is called on. - 3
Chain the toppings
addCheese()andaddBasil()each flip one field and return the builder again. There is noaddOlives()call: leaving an option out costs nothing. - 4
Validate and build
build()checks thatsizeis set, then createspizzain one go withsize = "small",cheese = true,olives = false,basil = true, the order the Before version got wrong. - 5
Use the product
kitchen.bake(pizza)callspizza.describe()and returns"baked small: cheese, basil". The kitchen never sees the builder. - 6
Refuse an invalid order
builder2gets cheese but no size. Itsbuild()throwsno sizebefore callingnew Pizza, the client catches it, and no half-made pizza ever exists. - 7
Same steps, another representation
In Director with Add bill applied,
chef.margherita(bill)runs the very same three steps on aBillBuilder:totalgoes 10, 12, 13, andbill.getTotal()returns13.Chefwas not edited.
Before and after
Positional constructor
- Values are matched by position; same-typed ones swap silently
- To set a late option you must write every earlier one
- Without default parameters: one overload per combination
- Setters instead mean a mutable, possibly half-built object
- One class, no extra code: fine for two or three parameters
With Builder
- Every value is named at the call site, in any order
- Defaults live in the builder; unwanted options are not called
build()validates the whole object before it exists- The product can be immutable, with no public half-built state
- Costs a second class that mirrors the product's fields
The Fluent change request adds an optional crust that defaults to classic. Here the numbers do not favor the pattern, and that is worth seeing:
| Change request: add crust | Before | With Builder |
|---|---|---|
| Existing classes edited | 1 (Pizza) | 2 (Pizza, PizzaBuilder) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 2 (+2 −0) | 9 (+8 −1) |
| The order that wants a thick crust | new Pizza("small", false, true, true, "thick") | one more line: .withCrust("thick") |
A builder duplicates the product's fields, so a new option is written twice: once in the product and once in the builder (a field, a method, and one more argument in build()). In TypeScript the Before version gets away with a trailing default parameter, so old call sites compile unchanged. What the builder buys is at the call sites: the thick-crust order in the Before run still carries the swapped booleans, now with a fifth positional value after them. In Java, which has no default parameters, the Before version would need another constructor overload or an edit to every call site.
The Director change request, Add bill, shows the GoF payoff: the price comes from a new BillBuilder (1 new class, 17 lines), and the director, the Builder interface and PizzaBuilder are untouched (0 existing classes edited).
Variations
| Variation | How it works | Use it when |
|---|---|---|
| Fluent builder | Steps return the builder (return this), build() returns the product | Most of the time: many optional parameters, readable call sites |
| GoF director | A director runs a fixed sequence of steps on an abstract builder; each concrete builder makes its own representation | One construction process must yield several unrelated results (object, text, price, preview) |
| Builder with required arguments | Required values go into the builder's constructor or a static factory (Pizza.builder("small")), optional ones into steps | A few values are mandatory and you want the compiler, not build(), to insist on them |
| Step builder | Each step returns a different interface that only offers the next legal step (size() returns NeedsCrust, which only has crust()...) | The order of steps matters and you want mistakes to be compile errors; costs one interface per step |
Copy builder (toBuilder()) | The immutable product returns a builder pre-filled with its own values; change one field and build() again | Making a slightly different copy of an immutable object |
| Generated builders | Lombok's @Builder (Java) or record/data-class tooling writes the builder for you; @Builder(toBuilder = true) adds the copy builder | The builder would be pure boilerplate with no validation logic |
| Named and default arguments | Kotlin, Python, C# and Swift let the caller write Pizza(size = "small", cheese = true) | The language supports it and you do not need step-by-step construction or a director; often this replaces the builder entirely |
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Pizza:
size: str
cheese: bool = False
olives: bool = False
basil: bool = False
# Keyword arguments name every value, defaults cover the rest.
p = Pizza(size="small", cheese=True, basil=True)
# A changed copy of an immutable object, like toBuilder():
with_olives = replace(p, olives=True)Builders also suit recursive structures: a builder for a menu, a document or a UI tree typically keeps a stack of open containers and adds children to the top one, so the result is a Composite. A query builder that accumulates where clauses is the same idea applied to an expression tree.
In real code
| Where | What it shows |
|---|---|
StringBuilder (Java, C#) | Mutable accumulation: append returns the builder, and the immutable String comes out of toString() at the end |
HttpRequest.newBuilder() (Java 11+) | Named steps for an immutable request; build() throws IllegalStateException if no URI was set |
Stream.Builder (Java) | Add elements one by one, then build(); adding after build() throws |
ProcessBuilder (Java) | Configure the command, directory and redirects once, then call start() any number of times to launch processes with the same settings |
Locale.Builder (Java 7+) | Each setter validates its value and throws IllformedLocaleException if it is malformed |
| Protocol Buffers (Java) | Generated newBuilder() for immutable messages, and toBuilder() for changed copies |
| Query builders and ORMs | Chained select, where, orderBy calls each add a part; the SQL is produced once, from the whole |
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/menu"))
.header("Accept", "application/json")
.GET()
.build();
Stream<String> s = Stream.<String>builder().add("a").add("b").build();
Process p = new ProcessBuilder("ls", "-l")
.directory(new File("/tmp"))
.redirectErrorStream(true)
.start();
Locale l = new Locale.Builder().setLanguage("en").setRegion("US").build();When to use it, and when not to
Reach for Builder when
- A constructor has more than about four parameters, especially several of the same type
- Many parameters are optional and have sensible defaults
- The product should be immutable but needs several steps to assemble
- The whole configuration must be validated before the object exists
- One construction process must produce several representations (the director form)
Skip it when
- There are two or three parameters: a plain constructor is clearer
- The language has named and default arguments and you need nothing else
- The object is a simple mutable data holder anyway
- A static factory with a good name (
Pizza.margherita()) covers the few common configurations
Builder vs similar patterns
| What it solves | How the object is made | Typical sign | |
|---|---|---|---|
| Builder | Complex construction: many options, validation, several steps | Configured step by step, created once by build() | .withX().withY().build() |
| Factory Method | Which concrete class to create | One call; a subclass picks the class | protected abstract createX() |
| Abstract Factory | A family of products that must match | One call per product on a factory object | factory.createButton(), factory.createCheckbox() |
| Prototype | Creating from an existing configured instance | Copy an example, then adjust | clone(); toBuilder() is the builder's version of it |
| Telescoping constructors | Optional parameters without a builder | Overloads that pass defaults to each other | Pizza(size), Pizza(size, cheese), Pizza(size, cheese, olives)... |
| Named arguments | Readable calls with defaults, built into the language | One constructor call, values named | Pizza(size = "small", cheese = true) |
The creational patterns combine. A builder's build() can use a Factory Method to pick the concrete product class, an Abstract Factory can hand out builders, and a builder that starts from an existing object (toBuilder()) plays the role of a Prototype. Keeping construction in its own object is also the single-responsibility idea from SOLID Principles: the product describes what it is, the builder knows how it is assembled.
Implementation
The visualizer's Fluent scenario with the crust change applied: an immutable Pizza that can only be created through PizzaBuilder, chained steps with defaults, and a build() that validates the order and throws instead of returning an invalid pizza.
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Pizza:
size: str
crust: str
cheese: bool
olives: bool
basil: bool
def describe(self) -> str:
t = [f"{self.crust} crust"]
if self.cheese:
t.append("cheese")
if self.olives:
t.append("olives")
if self.basil:
t.append("basil")
return f"{self.size}: {', '.join(t)}"
class PizzaBuilder:
def __init__(self) -> None:
self._size: Optional[str] = None
self._crust = "classic" # defaults live here
self._cheese = False
self._olives = False
self._basil = False
def with_size(self, s: str) -> PizzaBuilder:
self._size = s
return self
def with_crust(self, c: str) -> PizzaBuilder:
self._crust = c
return self
def add_cheese(self) -> PizzaBuilder:
self._cheese = True
return self
def add_olives(self) -> PizzaBuilder:
self._olives = True
return self
def add_basil(self) -> PizzaBuilder:
self._basil = True
return self
def build(self) -> Pizza:
if self._size is None:
raise ValueError("no size")
if self._size not in ("small", "large"):
raise ValueError(f"unknown size: {self._size}")
return Pizza(self._size, self._crust,
self._cheese, self._olives, self._basil)
pizza = (PizzaBuilder()
.with_size("small")
.with_crust("thick")
.add_cheese()
.add_basil()
.build())
print(pizza.describe()) # small: thick crust, cheese, basil
try:
PizzaBuilder().add_cheese().build()
except ValueError as e:
print(e) # no sizeKey takeaways
- A fluent builder replaces a long positional constructor with named, chainable steps and a final
build(), so call sites read like the order they describe. - Each step returns the builder itself (
return this); that is all method chaining is. build()is the one place that sees the whole configuration: validate there and throw, so no invalid or half-built product ever exists, and the product can stay immutable.- The GoF form adds a director that runs one recipe against an abstract builder; each concrete builder turns the same steps into a different representation (a
Pizzaor a price of 13). - A builder duplicates the product's fields: in the crust change request it touched 2 classes where the positional constructor touched 1. Its payoff is correct, readable call sites, not fewer edits.
- In languages with named and default arguments (Kotlin, Python, C#), those often make a fluent builder unnecessary.
Common pitfalls
- Validating in each setter only: rules that involve several fields ("olives need a large size") can only be checked in
build(). - Returning a product that shares mutable state with the builder (the same list object), so changing the builder after
build()changes the "immutable" product. Copy collections inbuild(). - Reusing one builder for several products without resetting it: the second
build()silently carries the first order's options. - Writing a builder for a class with two or three parameters, or one that only copies values with no defaults or validation: extra code, no benefit.
- Adding a field to the product and forgetting the builder (or the reverse). Generate builders where you can, and test that every field round-trips.
Interview tips
- Start from the pain: show a telescoping constructor with swapped booleans, then the builder call. Interviewers want to hear why, not just the shape.
- Distinguish the two forms: the fluent builder (Effective Java, readable immutable construction) and the GoF builder (director plus builders, same process, different representations).
- Mention
build()validation and immutability, and name the trade-off: a second class that mirrors the product's fields. - In LLD rounds, builders fit request and query objects, notifications with many optional fields, and test-data setup. Compare with named arguments if the interview language has them.
Real-world applications
- HTTP requests and clients configured step by step (
HttpRequest.newBuilder()in Java). - String and collection assembly (
StringBuilder,Stream.Builder). - SQL and search query builders that add clauses one call at a time.
- Generated immutable message types with builders and copy builders (Protocol Buffers, Lombok
@Builder). - Test-data builders that produce valid objects with defaults, overriding only what a test cares about.
- Document converters and exporters that turn one parsed structure into several output formats (the GoF director form).
Test yourself
What does new Pizza("small", false, true, true) in the Before version demonstrate?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.