November 24, 202614 minutes
Thirty, thin, true, false, true, true, true. Learn how the Builder pattern turns unreadable constructors into a readable, validated, immutable object: order step by step, bake once.
We’re ordering a pizza in Java: thirty centimeters, thin crust, and then… true, false, true, true, true. Does this pizza have olives? Is it gluten free? You can’t tell without opening the
class and counting parameters. Objects with many optional parts are everywhere, and there’s a
pattern for creating them without the mess: the Builder pattern.
Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.
Here’s a line of Java you’ve probably seen in some form:
Pizza p = new Pizza(30, "thin", true, false, true, true, true);The pizza has two required parts (a size in centimeters and a crust) and five optional ones:
cheese, pepperoni, mushrooms, olives and gluten-free. So which true is the olives? The call
site doesn’t say. You have to open the class and count.
And it gets worse. Swap two of those booleans by accident:
Pizza p = new Pizza(30, "thin", true, true, false, true, true);The code still compiles. Every argument still has the right type, so the compiler is happy. You just get the wrong pizza (pepperoni, no mushrooms), and nobody notices until it’s delivered.
Pizzas, HTTP requests, database connections, reports: objects with many optional parts are everywhere. How do you create them without this mess?
The first fix most of us reach for is overloading: a short constructor for the common case, and longer ones for more options. Each constructor passes a default to the next, longer one:
public Pizza(int size, String crust) {
this(size, crust, true);
}
public Pizza(int size, String crust, boolean cheese) {
this(size, crust, cheese, false);
}
public Pizza(int size, String crust, boolean cheese, boolean pepperoni) {
this(size, crust, cheese, pepperoni, false);
}
// ...three more, up to all seven parametersThat’s why it’s called a telescoping constructor: it slides out one parameter at a time.
It works for the simple cases. But say you want mushrooms, and nothing else special. Mushrooms come fifth, so you still have to pass cheese and pepperoni first, in the right order:
Pizza p = new Pizza(30, "thin", true, false, true); // just mushroomsWith seven options, that’s already six constructors, and every new option adds another one (and edits the chain). None of them fixes the real problem: a row of booleans that all look the same. (When one small change forces edits across many places, that’s the Shotgun Surgery smell.)
So let’s try the opposite: an empty constructor, and a setter for every field.
Pizza p = new Pizza();
p.setSize(30);
p.setCrust("thin");
p.setMushrooms(true);
p.setOlives(true);
p.setGlutenFree(true);Now every line says exactly what it sets. Much more readable! But look at what happens between those lines:
Pizza p = new Pizza();
p.setSize(30);
oven.bake(p); // no crust yet!
p.setCrust("thin");
menu.featured = p;
p.setPepperoni(true); // changes the pizza everyone sharesThree problems hide in there:
setPepperoni and change it for everybody. Its fields can’t be final.So we have two bad options. One is unreadable. The other is readable, but it leaves the object half built, and mutable.
| Telescoping constructors | JavaBeans setters | |
|---|---|---|
| Readable call site | ✗ values hide in positions | ✓ every line names its field |
| Same-type mix-ups caught | ✗ | ✓ |
| Object complete before use | ✓ | ✗ half built |
Immutable (final fields) | ✓ | ✗ |
| One place to validate | ✓ (the big constructor) | ✗ |
Think about how a real pizza counter works. You don’t hand the cook a row of trues and falses. And the cook doesn’t put a half-made pizza on the counter while you’re still thinking.
Instead, you give your order step by step: thirty centimeters, thin crust, mushrooms, olives, gluten-free. Each choice goes onto an order slip. The slip is allowed to change: you can add olives, or change your mind about them. Nothing has been baked yet.
When you say “that’s it”, the cook checks the slip and bakes the pizza once. And a baked pizza doesn’t change anymore.
That’s the key insight: separate the construction, which happens step by step, from the finished product, which is complete and immutable. The order slip is the builder. In code, it reads just like the order:
Pizza p = new Pizza.Builder(30, "thin")
.mushrooms()
.olives()
.glutenFree()
.build();Compare it with the line we started from. Same pizza, but every choice now has a name, the order doesn’t matter, and you only mention what you want.
Order step by step. Bake once.
Start with the product. The pizza’s fields are all final, and its constructor is
private: the only way to get a pizza is through the builder.
public final class Pizza {
private final int size;
private final String crust;
private final boolean cheese, pepperoni, mushrooms, olives, glutenFree;
private Pizza(Builder b) {
this.size = b.size;
this.crust = b.crust;
this.cheese = b.cheese;
this.pepperoni = b.pepperoni;
this.mushrooms = b.mushrooms;
this.olives = b.olives;
this.glutenFree = b.glutenFree;
}
// getters only, no setters
// public static class Builder { ... } lives in here
}The private constructor takes the builder and copies every choice from it. After that there are getters, but no setters. Once it’s made, it stays made.
The builder lives inside the pizza class, as a static nested class (so it can call the
private constructor, and so the name reads Pizza.Builder). The required parts, size and
crust, go into its constructor, so you can’t forget them. Every optional part gets a default,
and a method with a meaningful name:
public static class Builder {
private final int size;
private final String crust;
private boolean cheese = true;
private boolean pepperoni, mushrooms, olives, glutenFree;
public Builder(int size, String crust) {
this.size = size;
this.crust = crust;
}
public Builder noCheese() { cheese = false; return this; }
public Builder pepperoni() { pepperoni = true; return this; }
public Builder mushrooms() { mushrooms = true; return this; }
public Builder olives() { olives = true; return this; }
public Builder glutenFree() { glutenFree = true; return this; }Each method records the choice and then returns this, the builder itself. Returning
this is what lets you chain the calls: each step hands the same builder to the next step.
That’s the fluent style.
And finally, build(), the last method of the builder:
public Pizza build() {
if (size < 20 || size > 45)
throw new IllegalStateException("size must be 20 to 45 cm");
if (glutenFree && crust.equals("stuffed"))
throw new IllegalStateException("no gluten-free stuffed crust");
return new Pizza(this);
}
}This is the one moment when the order is complete, so it’s the perfect place to validate it.
Is the size between twenty and forty-five centimeters? Is the combination possible? A
sixty-centimeter order fails right here, before a broken pizza ever exists. If everything
checks out, build() calls the private constructor and hands you a finished, immutable pizza.
The structure in one picture:
What we just built is the modern style, made popular by Joshua Bloch’s book Effective Java. The original Gang of Four (1994) version looks a little different. There the builder is an interface of construction steps (size, crust, topping), and there’s a new role, the Director. It knows the recipe, the order of the steps, but not what’s being built:
interface PizzaBuilder {
void size(int cm);
void crust(String type);
void topping(String name);
}
class Kitchen { // the Director: knows the recipe
void margherita(PizzaBuilder b) {
b.size(30);
b.crust("thin");
b.topping("tomato");
b.topping("mozzarella");
b.topping("basil");
}
}Here the kitchen is the Director. Its margherita method calls the same steps every time:
size thirty, thin crust, tomato, mozzarella, basil. Now hand it different builders. A
PizzaMaker assembles a real pizza. A MenuCard writes the description for the menu:
Kitchen kitchen = new Kitchen();
PizzaMaker maker = new PizzaMaker();
kitchen.margherita(maker);
Pizza pizza = maker.getResult();
MenuCard card = new MenuCard();
kitchen.margherita(card);
String text = card.getResult(); // same recipe, menu textSame recipe, same steps, completely different products. (The Director only talks to the
interface;
dynamic dispatch picks the concrete builder’s
methods at run time.) Notice that getResult() is not on the interface: each builder returns
its own product type.
So the two styles solve different problems:
| GoF builder | Fluent (Bloch) builder | |
|---|---|---|
| Problem solved | one construction process, different representations | one object with many options, readable and safe |
| Roles | Director + Builder interface + concrete builders | product + nested builder |
| Who calls the steps | the Director | the client, in a chain |
| Typical result | whatever each builder produces (getResult()) | one validated, immutable object (build()) |
| Where you meet it | document converters, parsers, exporters | almost every modern Java API |
In modern Java you’ll mostly meet the second one.
Since Java 11, the built-in HTTP client (java.net.http) creates its requests with a builder:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/orders"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(orderJson))
.build();New builder; then the address, a content-type header, a ten-second timeout, and a POST body. Every part has a name, and you only mention the parts you need (the method defaults to GET, so a GET request can skip that line).
And build() checks the order, just like our pizza: forget the address, and build() throws
an IllegalStateException instead of sending a request to nowhere. The finished request is
immutable, so you can share it between threads and send it again and again.
A half-filled builder also makes a great template. Put the shared header and timeout into a
base builder, then copy() it and add the address for each request:
HttpRequest.Builder base = HttpRequest.newBuilder()
.header("Authorization", "Bearer " + token)
.timeout(Duration.ofSeconds(10));
HttpRequest orders = base.copy().uri(URI.create(API + "/orders")).build();
HttpRequest stock = base.copy().uri(URI.create(API + "/stock")).build();Why copy()? A builder is mutable: if you kept calling base.uri(...) directly, every request
would change the same shared slip. Copying keeps the template clean.
You’ll find builders all over Java: StringBuilder, Stream.builder(), Locale.Builder, and
Lombok’s @Builder annotation, which writes all of the builder code for you.
Builder is often confused with the factory patterns. They’re all creational patterns, but they answer different questions:
// Factory: which kind of pizza?
Pizza a = PizzaFactory.create("margherita");
// Abstract Factory: a matching family of products
MenuFactory menu = new ItalianMenu();
Pizza b = menu.createPizza();
Drink d = menu.createDrink();
// Builder: how to assemble one pizza, step by step
Pizza c = new Pizza.Builder(30, "thin").mushrooms().olives().build();| Factory | Abstract Factory | Builder | |
|---|---|---|---|
| Question | which kind? | which family? | how? |
| Calls | one | one per product | many steps + build() |
| Result | one of several classes | several matching objects | one complex object |
| Client controls | the name / type | the family | every part |
The two can also combine: a factory method can return a pre-filled builder (like
HttpRequest.newBuilder()), and a builder’s build() can use a factory internally.
A factory picks the kind. A builder assembles the parts.
A builder earns its extra class only when there’s something to gain:
record with one extra constructor does the job, in
five lines:public record Pizza(int size, String crust, boolean cheese) {
public Pizza(int size, String crust) {
this(size, crust, true);
}
}A common misconception: a builder doesn’t make anything immutable by itself. The product
still needs final fields, no setters, and its own copies of any lists it receives (otherwise
the caller can keep a reference and change the list after build(); use List.copyOf(...)).
A builder that returns a mutable object with setters gives you the nice call site, but none of
the safety.
Reach for a builder when there are many optional parts, several parameters of the same type, or rules that must be checked before the object exists.
Long constructors are unreadable, and setters leave objects half built. A builder collects the
choices step by step, validates them in build(), and returns one complete, immutable object.
this, all checks in build(), a private constructor and final fields in the product.Order step by step. Bake once.
For reference, here’s the whole Pizza with its nested builder (the same pieces as above, put
together, plus getters):
public final class Pizza {
private final int size;
private final String crust;
private final boolean cheese, pepperoni, mushrooms, olives, glutenFree;
private Pizza(Builder b) {
this.size = b.size;
this.crust = b.crust;
this.cheese = b.cheese;
this.pepperoni = b.pepperoni;
this.mushrooms = b.mushrooms;
this.olives = b.olives;
this.glutenFree = b.glutenFree;
}
public int size() { return size; }
public String crust() { return crust; }
public boolean cheese() { return cheese; }
public boolean pepperoni() { return pepperoni; }
public boolean mushrooms() { return mushrooms; }
public boolean olives() { return olives; }
public boolean glutenFree() { return glutenFree; }
public static class Builder {
private final int size;
private final String crust;
private boolean cheese = true;
private boolean pepperoni, mushrooms, olives, glutenFree;
public Builder(int size, String crust) {
this.size = size;
this.crust = crust;
}
public Builder noCheese() { cheese = false; return this; }
public Builder pepperoni() { pepperoni = true; return this; }
public Builder mushrooms() { mushrooms = true; return this; }
public Builder olives() { olives = true; return this; }
public Builder glutenFree() { glutenFree = true; return this; }
public Pizza build() {
if (size < 20 || size > 45)
throw new IllegalStateException("size must be 20 to 45 cm");
if (glutenFree && crust.equals("stuffed"))
throw new IllegalStateException("no gluten-free stuffed crust");
return new Pizza(this);
}
}
}And the two GoF builders from the Director example (here Pizza is a simple class with a
size, a crust and a list of toppings):
class PizzaMaker implements PizzaBuilder {
private int size;
private String crust;
private final List<String> toppings = new ArrayList<>();
public void size(int cm) { size = cm; }
public void crust(String type) { crust = type; }
public void topping(String name) { toppings.add(name); }
Pizza getResult() { return new Pizza(size, crust, List.copyOf(toppings)); }
}
class MenuCard implements PizzaBuilder {
private final StringBuilder text = new StringBuilder();
public void size(int cm) { text.append(cm).append(" cm, "); }
public void crust(String type) { text.append(type).append(" crust"); }
public void topping(String name) { text.append(", ").append(name); }
String getResult() { return text.toString(); } // "30 cm, thin crust, tomato, mozzarella, basil"
}