Builder Pattern

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.

Thirty, thin, true, false, true, true, true

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.

Both the intended call and the call with two booleans swapped pass the compiler's only check, that the types match, so both compile: one gives the right pizza, the other silently gives pepperoni and no mushrooms. Both the intended call and the call with two booleans swapped pass the compiler's only check, that the types match, so both compile: one gives the right pizza, the other silently gives pepperoni and no mushrooms.
The compiler checks types, not meaning.

Pizzas, HTTP requests, database connections, reports: objects with many optional parts are everywhere. How do you create them without this mess?

The first fix: telescoping constructors

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 parameters

That’s why it’s called a telescoping constructor: it slides out one parameter at a time.

A chain of six constructors, each calling the next longer one with a default: size and crust, then plus cheese, plus pepperoni, plus mushrooms, plus olives, and finally all seven parameters, which does the real work. A chain of six constructors, each calling the next longer one with a default: size and crust, then plus cheese, plus pepperoni, plus mushrooms, plus olives, and finally all seven parameters, which does the real work.
Each overload fills in one default and hands over to the next.

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 mushrooms

With 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.)

The second fix: JavaBeans setters

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 shares

Three problems hide in there:

  1. Half built. After the first two lines the object already exists, but it’s only half built: there’s no crust yet, and nothing stops someone from using it right now.
  2. Never finished (mutable). Because the setters stay around, the pizza is never really done. Long after it’s baked and shared with the rest of the program, anyone can still call setPepperoni and change it for everybody. Its fields can’t be final.
  3. No moment to validate. Is the size allowed? Is the combination possible? With setters there is no single moment when the object is complete, so there’s no good place to check.
Sequence: the client creates an empty pizza and sets the size; the oven bakes it before the crust is set; the client then sets the crust and publishes it as the featured pizza; later, other code calls setPepperoni and changes the pizza everyone shares. Sequence: the client creates an empty pizza and sets the size; the oven bakes it before the crust is set; the client then sets the crust and publishes it as the featured pizza; later, other code calls setPepperoni and changes the pizza everyone shares.
A setter-built object exists, and is used, before it's finished, and stays changeable afterwards.

So we have two bad options. One is unreadable. The other is readable, but it leaves the object half built, and mutable.

Telescoping constructorsJavaBeans 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)✗

The key insight: an order slip

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.

The analogy mapped onto code: the order slip is the builder, saying that's it is calling build, and the baked pizza is the immutable Pizza object. The analogy mapped onto code: the order slip is the builder, saying that's it is calling build, and the baked pizza is the immutable Pizza object.
The order slip is the builder.

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.

Building it: the fluent builder

The product

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

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.

Sequence: the client creates a Pizza.Builder with 30 and thin; mushrooms, olives and glutenFree each return the same builder; build validates the order and calls the private Pizza constructor, which returns the finished pizza to the client. Sequence: the client creates a Pizza.Builder with 30 and thin; mushrooms, olives and glutenFree each return the same builder; build validates the order and calls the private Pizza constructor, which returns the finished pizza to the client.
Every step returns the same builder; only build() creates the pizza.

build(): validate once

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.

State diagram of a builder: it starts collecting choices, each step returns to collecting, build moves it to checking, a valid order becomes a Pizza, and an invalid one, such as 60 cm, is rejected with an IllegalStateException. State diagram of a builder: it starts collecting choices, each step returns to collecting, build moves it to checking, a valid order becomes a Pizza, and an invalid one, such as 60 cm, is rejected with an IllegalStateException.
Choices can change until build(); after that you either get a valid pizza or nothing.

The structure in one picture:

Class diagram: Pizza has final fields and a private constructor taking a Builder; the nested static class Pizza.Builder has the required size and crust, defaulted options, fluent methods returning Builder, and build returning Pizza; the builder creates the pizza. Class diagram: Pizza has final fields and a private constructor taking a Builder; the nested static class Pizza.Builder has the required size and crust, defaulted options, fluent methods returning Builder, and build returning Pizza; the builder creates the pizza.
The fluent builder: a nested class that is the only way to create the product.

Two kinds of builder: GoF Director vs fluent

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 text

Same 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.

Class diagram of the GoF Builder: Kitchen, the Director, uses the PizzaBuilder interface with size, crust and topping; PizzaMaker and MenuCard implement it; PizzaMaker's getResult returns a Pizza and MenuCard's getResult returns a String. Class diagram of the GoF Builder: Kitchen, the Director, uses the PizzaBuilder interface with size, crust and topping; PizzaMaker and MenuCard implement it; PizzaMaker's getResult returns a Pizza and MenuCard's getResult returns a String.
GoF Builder: one Director, one step interface, a concrete builder per product.

So the two styles solve different problems:

Comparison: the GoF builder reuses one construction process, the Director's recipe, for different products such as a pizza and a menu text; the fluent builder makes one object with many options readable and safe, ending in one validated immutable object. Comparison: the GoF builder reuses one construction process, the Director's recipe, for different products such as a pizza and a menu text; the fluent builder makes one object with many options readable and safe, ending in one validated immutable object.
Same name, two different problems.
GoF builderFluent (Bloch) builder
Problem solvedone construction process, different representationsone object with many options, readable and safe
RolesDirector + Builder interface + concrete buildersproduct + nested builder
Who calls the stepsthe Directorthe client, in a chain
Typical resultwhatever each builder produces (getResult())one validated, immutable object (build())
Where you meet itdocument converters, parsers, exportersalmost every modern Java API

In modern Java you’ll mostly meet the second one.

A builder you already use: HttpRequest

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();
A base builder holding the Authorization header and a 10 second timeout is copied twice: one copy gets the /orders URI and builds the orders request, the other gets the /stock URI and builds the stock request. A base builder holding the Authorization header and a 10 second timeout is copied twice: one copy gets the /orders URI and builds the orders request, the other gets the /stock URI and builds the stock request.
A half-filled builder is a template: copy it, finish it, build it.

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 vs Factory vs Abstract Factory

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();
  • A factory answers which kind? You ask for a margherita, and it decides which class to create. One call, and you’re done.
  • An abstract factory answers which family? An Italian menu gives you an Italian pizza and an Italian drink that belong together.
  • A builder answers how? It assembles one complex object, step by step, and you control every step.
Decision flowchart: if the question is which class to create, use a Factory; if it is which family of matching objects, use an Abstract Factory; if it is how to assemble one complex object step by step, use a Builder. Decision flowchart: if the question is which class to create, use a Factory; if it is which family of matching objects, use an Abstract Factory; if it is how to assemble one complex object step by step, use a Builder.
Three creational patterns, three questions.
FactoryAbstract FactoryBuilder
Questionwhich kind?which family?how?
Callsoneone per productmany steps + build()
Resultone of several classesseveral matching objectsone complex object
Client controlsthe name / typethe familyevery 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.

When not to use it

A builder earns its extra class only when there’s something to gain:

  • Two or three parameters, all required? A plain constructor is clearer. A builder would only add a second class to maintain (every field is written twice).
  • Just data with a few defaults? A Java 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.

Decision flowchart: with only two or three required parameters, use a constructor; for plain data with a few defaults, use a record; with many optional parts, same-typed parameters, or rules to check before the object exists, use a builder. Decision flowchart: with only two or three required parameters, use a constructor; for plain data with a few defaults, use a record; with many optional parts, same-typed parameters, or rules to check before the object exists, use a builder.
When a builder pays for itself.

Recap

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.

Recap chain: telescoping constructors and setters both fail; the order slip, the builder, collects choices step by step; build validates once; the result is a complete, immutable pizza. Recap chain: telescoping constructors and setters both fail; the order slip, the builder, collects choices step by step; build validates once; the result is a complete, immutable pizza.
Order step by step. Bake once.
  • Telescoping constructors hide meaning in positions and multiply with every option.
  • Setters are readable, but the object is half built, mutable, and never validated.
  • Builder: required parts in the builder’s constructor, options as named methods that return this, all checks in build(), a private constructor and final fields in the product.
  • The GoF builder (Director + step interface) reuses one process for different products; the fluent builder makes one object with many options readable and safe.
  • A factory picks the kind; a builder assembles the parts.

Order step by step. Bake once.

Complete code

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"
}