# Builder PatternThirty, 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**.

{{< lesson-video youtube="LVD-pm8fpcA" title="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:

```java
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:

```java
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.

```mermaid {alt="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." caption="The compiler checks types, not meaning."}
flowchart TD
  A["intended call<br/>true, false, true, true, true"] --> Q{"Do the argument<br/>types match?"}
  B["two booleans swapped<br/>true, true, false, true, true"] --> Q
  Q -->|"yes: compiles"| R["right pizza"]
  Q -->|"yes: compiles"| W["wrong pizza:<br/>pepperoni, no mushrooms"]
  class R good
  class W bad
  class Q hl
```

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:

```java
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.

```mermaid {alt="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." caption="Each overload fills in one default and hands over to the next."}
flowchart TD
  A["Pizza(size, crust)"] -->|"this(…, true)"| B["+ cheese"]
  B -->|"this(…, false)"| C["+ pepperoni"]
  C -->|"this(…, false)"| D["+ mushrooms"]
  D -->|"this(…, false)"| E["+ olives"]
  E -->|"this(…, false)"| F["all 7 parameters:<br/>does the real work"]
  class A,B,C,D,E c1
  class F hl
```

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:

```java
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](/code-smells/shotgun-surgery/) smell.)

## The second fix: JavaBeans setters

So let's try the opposite: an empty constructor, and a setter for every field.

```java
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:

```java
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.

```mermaid {alt="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." caption="A setter-built object exists, and is used, before it's finished, and stays changeable afterwards."}
sequenceDiagram
  participant C as Client
  participant P as Pizza
  participant O as Oven
  participant M as Menu
  C->>P: new Pizza()
  C->>P: setSize(30)
  C->>O: bake(p)
  Note over P,O: half built: no crust yet
  C->>P: setCrust("thin")
  C->>M: featured = p
  C->>P: setPepperoni(true)
  Note over P,M: the shared pizza changed for everyone
```

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

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

```mermaid {alt="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." caption="The order slip is the builder."}
flowchart LR
  subgraph COUNTER["At the pizza counter"]
    direction TB
    S["order slip<br/>(may still change)"] --> T["“That's it!”<br/>cook checks the slip"]
    T --> B["baked pizza<br/>(doesn't change)"]
  end
  subgraph CODE["In the code"]
    direction TB
    PB["Pizza.Builder<br/>(mutable)"] --> BU["build()<br/>validates"]
    BU --> PZ["Pizza<br/>(immutable)"]
  end
  COUNTER ~~~ CODE
  class S,PB c4
  class T,BU hl
  class B,PZ c2
```

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:

```java
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.

```java
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:

```java
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.

```mermaid {alt="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." caption="Every step returns the same builder; only build() creates the pizza."}
sequenceDiagram
  participant C as Client
  participant B as Pizza.Builder
  participant P as Pizza
  C->>B: new Pizza.Builder(30, "thin")
  C->>B: mushrooms()
  B-->>C: this
  C->>B: olives()
  B-->>C: this
  C->>B: glutenFree()
  B-->>C: this
  C->>B: build()
  Note over B: validate the whole order
  B->>P: new Pizza(this)
  P-->>C: finished, immutable pizza
```

### build(): validate once

And finally, `build()`, the last method of the builder:

```java
    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.

```mermaid {alt="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." caption="Choices can change until build(); after that you either get a valid pizza or nothing."}
stateDiagram-v2
  [*] --> Collecting: new Pizza.Builder(30, "thin")
  Collecting --> Collecting: mushrooms(), olives(), ...
  Collecting --> Checking: build()
  Checking --> Pizza: valid
  Checking --> Rejected: invalid (e.g. 60 cm)
  Pizza --> [*]
  class Collecting c4
  class Checking hl
  class Pizza c2
  class Rejected bad
```

The structure in one picture:

```mermaid {alt="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." caption="The fluent builder: a nested class that is the only way to create the product."}
classDiagram
  class Pizza {
    -int size
    -String crust
    -boolean cheese, pepperoni, mushrooms, olives, glutenFree
    -Pizza(Builder b)
  }
  class Builder {
    -int size
    -String crust
    -boolean cheese = true
    +Builder(int size, String crust)
    +noCheese() Builder
    +mushrooms() Builder
    +olives() Builder
    +glutenFree() Builder
    +build() Pizza
  }
  Builder ..> Pizza : creates (only way)
  note for Builder "static nested class: Pizza.Builder"
```

## 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:

```java
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:

```java
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](/fundamentals/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.

```mermaid {alt="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." caption="GoF Builder: one Director, one step interface, a concrete builder per product."}
classDiagram
  class Kitchen {
    +margherita(PizzaBuilder b)
  }
  class PizzaBuilder {
    <<interface>>
    +size(int cm)
    +crust(String type)
    +topping(String name)
  }
  class PizzaMaker {
    +getResult() Pizza
  }
  class MenuCard {
    +getResult() String
  }
  Kitchen o--> PizzaBuilder : directs
  PizzaBuilder <|.. PizzaMaker
  PizzaBuilder <|.. MenuCard
  note for Kitchen "Director: knows the recipe, not the product"
```

So the two styles solve different problems:

```mermaid {alt="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." caption="Same name, two different problems."}
flowchart LR
  subgraph GOF["GoF builder"]
    direction TB
    R["one recipe<br/>(Director)"] --> P1["PizzaMaker → Pizza"]
    R --> P2["MenuCard → menu text"]
  end
  subgraph FLU["Fluent builder"]
    direction TB
    O["many options,<br/>named steps"] --> V["build() validates"]
    V --> I["one immutable object"]
  end
  GOF ~~~ FLU
  class R c5
  class P1 c4
  class P2 c6
  class O c4
  class V hl
  class I c2
```

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

## A builder you already use: HttpRequest

Since Java 11, the built-in HTTP client (`java.net.http`) creates its requests with a builder:

```java
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:

```java
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();
```

```mermaid {alt="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." caption="A half-filled builder is a template: copy it, finish it, build it."}
flowchart TD
  B["base builder<br/>Authorization header, 10 s timeout"] -->|"copy() + uri /orders"| O["orders request"]
  B -->|"copy() + uri /stock"| S["stock request"]
  class B c4
  class O,S c2
```

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:

```java
// 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.

```mermaid {alt="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." caption="Three creational patterns, three questions."}
flowchart TD
  Q{"What does the caller<br/>need to decide?"}
  Q -->|"which kind?"| F["Factory<br/>one call → one of several classes"]
  Q -->|"which family?"| AF["Abstract Factory<br/>matching pizza + drink"]
  Q -->|"how, step by step?"| B["Builder<br/>one object, many parts"]
  class F c1
  class AF c5
  class B c4
```

| | Factory | [Abstract Factory](/patterns/abstract-factory-pattern/) | 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.**

## 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:

```java
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**.

```mermaid {alt="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." caption="When a builder pays for itself."}
flowchart TD
  Q1{"More than 3 parameters,<br/>or several optional ones?"}
  Q1 -->|no| K1["Plain constructor"]
  Q1 -->|yes| Q2{"Just data with<br/>a few defaults?"}
  Q2 -->|yes| K2["record + extra constructor"]
  Q2 -->|"no: same-type params,<br/>rules to check, immutability"| U["Builder"]
  class U good
  class K1,K2 muted
```

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

```mermaid {alt="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." caption="Order step by step. Bake once."}
flowchart LR
  X["long constructors ✗<br/>setters ✗"] --> S["builder:<br/>step by step"]
  S --> B["build():<br/>validate once"]
  B --> P["complete,<br/>immutable object"]
  class X bad
  class S c4
  class B hl
  class P c2
```

- **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):

```java
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):

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