These are the notes for Low-Level Design (LLD) episode 25. The last two episodes decided which class to create. Today is about how to create one object that has many parts, most of them optional. We start with an order slip at a dosa counter, watch an eight-argument constructor silently swap two values, see why telescoping constructors and JavaBeans setters both go wrong, then invent the Builder: a static nested class whose constructor takes the required values, whose optional values are named steps that return this (a fluent interface built by method chaining), and whose build() validates everything once before creating an immutable object. Then the director, the JDK's own HttpRequest builder, and Lombok @Builder. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.
1. The real-life idea: an order slip
| At the dosa counter | In code |
|---|---|
| The order slip: dish and table number are a must | A builder: collects the parts of an object before the object is made |
| Tick boxes: extra butter, less spicy, no onion | Optional parts: each has a name, any order, skip what you don't want |
| The cashier checks the slip ("spice 9? we only go up to 3") | build() validates: a bad order never becomes an object |
| The dosa arrives; you can't untick the onions | Immutable result: the finished object can't change |
An object is immutable when none of its fields can change after it has been created (episode 6). A String is the classic example.
2. Attempt 1: one big constructor
Priya's food app needs an Order with eight values: item, address, quantity, spice level, extra cheese, no onion, a note for the rider, and a coupon. The obvious way is one constructor that takes all eight:
class Order {
String item, address; int qty, spice; boolean cheese, noOnion; String note, coupon;
Order(String item, String address, int qty, int spice, boolean cheese,
boolean noOnion, String note, String coupon) {
this.item = item; this.address = address; this.qty = qty; this.spice = spice;
this.cheese = cheese; this.noOnion = noOnion; this.note = note; this.coupon = coupon;
}
public String toString() {
return qty + " x " + item + " | spice " + spice + " | cheese " + cheese
+ " | onion " + !noOnion + " | to " + address;
}
}
public class Main {
public static void main(String[] args) {
// Priya wants: extra cheese, WITH onion
Order o = new Order("Paneer wrap", "12 MG Road", 2, 1, false, true, null, null);
System.out.println(o);
}
}
2 x Paneer wrap | spice 1 | cheese false | onion false | to 12 MG Road
She wanted extra cheese (cheese = true) with onion (noOnion = false), so the right call was ..., true, false, .... She typed false, true: the two booleans swapped places, and the order came out with no cheese and no onion, the exact opposite. The compiler can't help, because both parameters are boolean: arguments of the same type can be swapped silently, and a call like false, true, null, null tells the reader nothing.
The telescoping constructor anti-pattern
The usual patch is more constructors, each one a little longer, like a telescope sliding open:
Order(String item, String address)
Order(String item, String address, int qty)
Order(String item, String address, int qty, int spice)
Order(String item, String address, int qty, int spice, boolean cheese, boolean noOnion, String note, String coupon)
This is the telescoping constructor anti-pattern. An anti-pattern is a common solution that looks fine but causes trouble (episode 21). Problems:
- Arguments are positional: their meaning comes only from their place in the list.
- To pass only a coupon you still pass every value before it.
- Eight options would need dozens of constructors to cover the useful combinations.
3. Attempt 2: JavaBeans setters
JavaBeans is an old Java naming convention: a class with a no-argument (empty) constructor and a setX/getX method for each field. Every value now has a name:
class Order {
private String item, address; private int qty = 1; private boolean cheese;
public Order() { } // JavaBeans style: empty object first
public void setItem(String item) { this.item = item; }
public void setAddress(String address) { this.address = address; }
public void setQty(int qty) { this.qty = qty; }
public void setExtraCheese(boolean c) { this.cheese = c; }
public String toString() { return qty + " x " + item + " | cheese " + cheese + " | to " + address; }
}
public class Main {
public static void main(String[] args) {
Order o = new Order();
o.setItem("Paneer wrap");
o.setQty(2);
o.setExtraCheese(true); // forgot setAddress(...)
System.out.println("Placed: " + o);
o.setQty(20); // anyone can change it later
System.out.println("Kitchen sees: " + o);
}
}
Placed: 2 x Paneer wrap | cheese true | to null
Kitchen sees: 20 x Paneer wrap | cheese true | to null
This is the JavaBeans setter problem:
- The object exists while it is half-built, so nothing forces the address:
to null, no error. - Because it has setters, it is mutable: any code can change it after it was placed (2 wraps became 20).
- Rules (quantity 1 to 10) would have to be checked in every setter, and rules that involve two fields at once have no good place to live.
Why both attempts failed
| Big constructor | Setters | |
|---|---|---|
| Values have names? | No (positional) | Yes |
| Required values forced? | Yes | No (half-built object) |
| One place to check rules? | Only in the constructor | No |
| Finished object can change? | Depends | Yes |
We want: named steps (like tick boxes), one check at the end (like the cashier), then a finished object nobody can change.
4. The fix: a static nested builder
final class Order {
private final String item, address;
private final int qty, spice; private final boolean cheese, noOnion;
private Order(Builder b) { item = b.item; address = b.address; qty = b.qty; // only the builder calls this
spice = b.spice; cheese = b.cheese; noOnion = b.noOnion; }
public String toString() { return qty + " x " + item + " | spice " + spice
+ " | cheese " + cheese + " | onion " + !noOnion + " | to " + address; }
static class Builder { // static nested builder
private final String item, address; // required
private int qty = 1, spice = 1; private boolean cheese, noOnion; // optional
Builder(String item, String address) { this.item = item; this.address = address; }
Builder qty(int q) { qty = q; return this; } Builder spice(int s) { spice = s; return this; }
Builder extraCheese() { cheese = true; return this; } Builder noOnion() { noOnion = true; return this; }
Order build() { // check everything, once
check(qty >= 1 && qty <= 10, "qty must be 1-10, got " + qty);
check(spice >= 0 && spice <= 3, "spice must be 0-3, got " + spice);
return new Order(this);
}
static void check(boolean ok, String msg) { if (!ok) throw new IllegalStateException(msg); }
}
}
public class Main {
public static void main(String[] args) {
Order o = new Order.Builder("Paneer wrap", "12 MG Road").qty(2).extraCheese().noOnion().build();
System.out.println(o);
System.out.println(new Order.Builder("Masala dosa", "4 Park St").build());
}
}
2 x Paneer wrap | spice 1 | cheese true | onion false | to 12 MG Road
1 x Masala dosa | spice 1 | cheese false | onion true | to 4 Park St
How each piece works:
final class Orderwithprivate finalfields: once built, nothing can change it. That makes it an immutable result object.private Order(Builder b): nobody outside can callnew Order(...), so nobody can skip the checks.static class Builder: a static nested class is a class written inside another class and markedstatic, so you can create it without anOrderexisting (new Order.Builder(...)). It can still reachOrder's private constructor because it lives insideOrder.- Required vs optional parameters: required values (
item,address) go into the builder's constructor, so you cannot even start without them. Optional values get defaults (qty = 1,spice = 1) and a named method each. return this: each optional method returns the builder itself, so the calls can follow one another:.qty(2).extraCheese().noOnion(). That is method chaining, and an API designed to be read like a sentence this way is a fluent interface.build()checks every rule once (build-time validation), then calls the private constructor.
5. Validation in build()
final class Order {
private final String item, address;
private final int qty, spice; private final boolean cheese, noOnion;
private Order(Builder b) { item = b.item; address = b.address; qty = b.qty; // only the builder calls this
spice = b.spice; cheese = b.cheese; noOnion = b.noOnion; }
public String toString() { return qty + " x " + item + " | spice " + spice
+ " | cheese " + cheese + " | onion " + !noOnion + " | to " + address; }
static class Builder { // static nested builder
private final String item, address; // required
private int qty = 1, spice = 1; private boolean cheese, noOnion; // optional
Builder(String item, String address) { this.item = item; this.address = address; }
Builder qty(int q) { qty = q; return this; } Builder spice(int s) { spice = s; return this; }
Builder extraCheese() { cheese = true; return this; } Builder noOnion() { noOnion = true; return this; }
Order build() { // check everything, once
check(qty >= 1 && qty <= 10, "qty must be 1-10, got " + qty);
check(spice >= 0 && spice <= 3, "spice must be 0-3, got " + spice);
return new Order(this);
}
static void check(boolean ok, String msg) { if (!ok) throw new IllegalStateException(msg); }
}
}
public class Main {
public static void main(String[] args) {
Order ok = new Order.Builder("Paneer wrap", "12 MG Road").qty(2).build();
System.out.println(ok);
Order bad = new Order.Builder("Veg biryani", "7 Ring Rd").qty(2).spice(9).build();
System.out.println(bad);
}
}
2 x Paneer wrap | spice 1 | cheese false | onion true | to 12 MG Road
Exception in thread "main" java.lang.IllegalStateException: spice must be 0-3, got 9
at Order$Builder.check(Main.java:19)
at Order$Builder.build(Main.java:16)
at Main.main(Main.java:26)
IllegalStateException is Java's standard unchecked exception for "this object is not in a state where that call makes sense" (here: the builder holds an invalid order). The bad order never became an object. Order$Builder in the stack trace is how the JVM names the nested class Builder inside Order.
Why validate in build() and not in each step? A rule that involves two values together (for example "no extra cheese when spice is 3") can only be checked when all values are known, and build() is the one place where they are.
| Constructor call | Builder call |
|---|---|
new Order("Paneer wrap", "12 MG Road", 2, 1, false, true, null, null) |
new Order.Builder("Paneer wrap", "12 MG Road").qty(2).extraCheese().noOnion().build() |
| Positional, easy to swap | Named, checked, immutable |
6. It has a name: the Builder pattern
The Gang of Four (GoF) intent: "separate the construction of a complex object from its representation." In plain words: the steps to make an object live in one class (the builder), and the finished object in another (the product).
| Role | In our code | Job |
|---|---|---|
| Product | Order |
The finished, immutable object |
| Builder | Order.Builder |
Collects the parts step by step; build() hands over the product |
| Director (optional) | Combos |
Knows a fixed recipe of steps and runs them on a builder |
| Client | Main |
Uses the builder directly, or asks the director |
Note that the builder is mutable while you fill it in; only the product is immutable. The slip changes, the dosa doesn't. Classic descriptions list the costs too: one builder class per product, and builders are mutable.
7. The director: saved recipes
A director is a class that knows a fixed sequence of builder steps. Priya's combos are always built the same way:
final class Order {
private final String item, address;
private final int qty, spice; private final boolean cheese, noOnion;
private Order(Builder b) { item = b.item; address = b.address; qty = b.qty; // only the builder calls this
spice = b.spice; cheese = b.cheese; noOnion = b.noOnion; }
public String toString() { return qty + " x " + item + " | spice " + spice
+ " | cheese " + cheese + " | onion " + !noOnion + " | to " + address; }
static class Builder { // static nested builder
private final String item, address; // required
private int qty = 1, spice = 1; private boolean cheese, noOnion; // optional
Builder(String item, String address) { this.item = item; this.address = address; }
Builder qty(int q) { qty = q; return this; } Builder spice(int s) { spice = s; return this; }
Builder extraCheese() { cheese = true; return this; } Builder noOnion() { noOnion = true; return this; }
Order build() { /* same checks as before */ return new Order(this); }
}
}
class Combos { // the director: fixed recipes of steps
static Order kidsMeal(String to) {
return new Order.Builder("Cheese sandwich", to).spice(0).extraCheese().build(); }
static Order partyPack(String item, String to) {
return new Order.Builder(item, to).qty(10).spice(2).noOnion().build(); }
}
public class Main {
public static void main(String[] args) {
System.out.println(Combos.kidsMeal("12 MG Road"));
System.out.println(Combos.partyPack("Paneer wrap", "4 Park St"));
}
}
1 x Cheese sandwich | spice 0 | cheese true | onion true | to 12 MG Road
10 x Paneer wrap | spice 2 | cheese false | onion false | to 4 Park St
The recipe is written once; change the party pack in one place and every screen that sells it changes. In the GoF version the director works with a builder interface, so the same recipe can drive different builders (for example one that builds an Order and one that builds a printable kitchen ticket). In everyday Java the director is optional, and most builders don't have one.
8. A builder inside the JDK: HttpRequest
java.net.http.HttpRequest (Java 11+) describes a web request. You don't call a constructor; you use its builder. Nothing is sent here, we only build the request object:
import java.net.URI;
import java.net.http.HttpRequest;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
HttpRequest req = HttpRequest.newBuilder() // the JDK's own builder
.uri(URI.create("https://syntaxpilot.in/notes"))
.header("Accept", "text/html")
.timeout(Duration.ofSeconds(5))
.GET()
.build(); // nothing is sent: we only build it
System.out.println(req.method() + " " + req.uri());
System.out.println(req.headers().map());
HttpRequest noUri = HttpRequest.newBuilder().GET().build(); // a required part missing
}
}
GET https://syntaxpilot.in/notes
{Accept=[text/html]}
Exception in thread "main" java.lang.IllegalStateException: uri is null
at java.net.http/jdk.internal.net.http.HttpRequestBuilderImpl.build(HttpRequestBuilderImpl.java:222)
at Main.main(Main.java:15)
Same idea as ours: named chained steps, and build() refuses an object that is missing a required part. StringBuilder (new StringBuilder().append("a").append(1)) also uses method chaining, but it is a mutable text buffer rather than a builder for a separate immutable product.
9. Lombok @Builder
Lombok is a popular open-source Java library that generates repetitive code for you. An annotation is a label starting with @ that tools can read (@Override is one). With @Builder on a class:
@Builder
class Order {
String item, address;
int qty, spice;
}
// Lombok generates OrderBuilder, one chained method per field, build(), and Order.builder(), so you can write:
Order o = Order.builder().item("Paneer wrap").address("12 MG Road").qty(2).build();
(This snippet needs the Lombok library added to the project, so it does not compile with plain javac; that's why it isn't run here.) According to the Lombok documentation, @Builder generates an inner static class named <Type>Builder, one method per field that "returns the builder itself", a build() method and a static builder() method; @Builder(toBuilder = true) also adds toBuilder(), which starts a new builder from an existing object's values, and @Singular gives one-at-a-time adder methods for collection fields.
Two cautions: generated build() does not know your business rules (quantity 1 to 10), and required fields are not forced unless you add checks. In a machine-coding round, write the builder by hand so the interviewer sees you understand it.
10. When to use a builder, and when not
Use it when:
- a class has many parameters (as a rule of thumb, four or more), most of them optional;
- several parameters have the same type and could be swapped silently;
- there are rules to check before the object exists, especially rules over several values;
- you want the finished object to be immutable.
Don't use it when: the class has two or three required values (a constructor is clearer). The cost is an extra class, and each new field must be added in two places.
Common mistakes
| Mistake | Exact message / symptom | Why | Fix |
|---|---|---|---|
Optional step returns void |
error: void cannot be dereferenced on .qty(2).extraCheese() |
Chaining needs each step to return the builder | return this; |
| Swapped same-type arguments in a long constructor | no error: cheese false when you meant true |
Positional arguments | Named builder steps |
| Required values as optional steps | no error: an order with to null |
Nothing forces them | Put them in the builder's constructor |
| Product constructor left public | no error: unchecked Orders appear |
build() can be skipped |
Make the product's constructor private |
| Checks only inside each step | no error: an invalid combination slips through | Rules over two values need all values | Validate in build() |
| Invalid value | java.lang.IllegalStateException: spice must be 0-3, got 9 |
The rule in build() fired (correct behaviour) |
Pass a valid value |
| Product has setters | no error: the order changes after it is placed | Not immutable | final fields, no setters |
The void cannot be dereferenced message is real:
Main.java:2: error: void cannot be dereferenced
public class Main { public static void main(String[] a) { new B().qty(2).cheese(); } }
^
1 error
Mini project: a pizza builder
Build an immutable Pizza with a required size ("S", "M", "L") and optional crust (default "thin"), toppings (a list, added one at a time) and extraCheese. Rules in build(): size must be S, M or L; at most 5 toppings; a small pizza can't have more than 3 toppings. The product must not share its toppings list with the builder.
Solution
import java.util.*;
final class Pizza {
private final String size, crust; private final List<String> toppings; private final boolean cheese;
private Pizza(Builder b) {
size = b.size; crust = b.crust; cheese = b.cheese;
toppings = List.copyOf(b.toppings); // an unmodifiable copy: the builder can't change it later
}
public String toString() { return size + " " + crust + " crust " + toppings + (cheese ? " + extra cheese" : ""); }
static class Builder {
private final String size; private String crust = "thin"; private boolean cheese;
private final List<String> toppings = new ArrayList<>();
Builder(String size) { this.size = size; }
Builder crust(String c) { crust = c; return this; }
Builder topping(String t) { toppings.add(t); return this; }
Builder extraCheese() { cheese = true; return this; }
Pizza build() {
if (!List.of("S", "M", "L").contains(size)) throw new IllegalStateException("size must be S, M or L, got " + size);
if (toppings.size() > 5) throw new IllegalStateException("at most 5 toppings, got " + toppings.size());
if (size.equals("S") && toppings.size() > 3) throw new IllegalStateException("a small pizza takes at most 3 toppings");
return new Pizza(this);
}
}
}
public class Main {
public static void main(String[] args) {
Pizza.Builder b = new Pizza.Builder("M").crust("pan").topping("paneer").topping("onion");
Pizza p = b.extraCheese().build();
b.topping("corn"); // changing the builder after build()
System.out.println(p); // the pizza is unchanged
try {
new Pizza.Builder("S").topping("a").topping("b").topping("c").topping("d").build();
} catch (IllegalStateException e) { System.out.println("rejected: " + e.getMessage()); }
}
}
M pan crust [paneer, onion] + extra cheese
rejected: a small pizza takes at most 3 toppings
List.copyOf makes an unmodifiable copy, so the finished pizza is truly immutable even though the builder's list keeps changing.
Practice
1. Add a coupon(String code) step to the order builder that rejects an empty code. Where should the check go, and what happens with .coupon("")?
Answer
Either in the step or in build(); a single-value rule can live in the step, but keeping all rules in build() gives one place to read them. Run:
final class Order {
private final String item, coupon;
private Order(Builder b) { item = b.item; coupon = b.coupon; }
public String toString() { return item + (coupon == null ? "" : " with coupon " + coupon); }
static class Builder {
private final String item; private String coupon;
Builder(String item) { this.item = item; }
Builder coupon(String code) { coupon = code; return this; }
Order build() {
if (coupon != null && coupon.isBlank()) throw new IllegalStateException("coupon code is empty");
return new Order(this);
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Order.Builder("Thali").coupon("SAVE10").build());
System.out.println(new Order.Builder("Thali").build());
System.out.println(new Order.Builder("Thali").coupon("").build());
}
}
Thali with coupon SAVE10
Thali
Exception in thread "main" java.lang.IllegalStateException: coupon code is empty
2. Add the rule "no extra cheese when spice is 3". Why can't it go inside extraCheese()?
Answer
Because the caller may call .extraCheese() before .spice(3); at that moment spice is still the default. Only build() sees the final values:
check(!(cheese && spice == 3), "extra cheese is not available at spice 3");
3. Why is Order's constructor private, and how can Builder still call it?
Answer
So that no code can create an Order without going through build() and its checks. A nested class is part of its enclosing class, so it may use the enclosing class's private members.
4. Is the builder itself immutable? Should it be?
Answer
No. The builder is filled in step by step, so it must be mutable. Only the product is immutable. Don't share one builder between threads or reuse it carelessly; make a new one per object.
5. A class Point(int x, int y) has two required ints. Builder or constructor?
Answer
A constructor (or a static factory like Point.of(x, y)). Two required values don't justify an extra class. A builder pays off with many, mostly optional, parameters.
Quick quiz
Order o = new Order.Builder("Thali", "9 Lake Rd")
.spice(2)
.qty(0)
.build();
System.out.println(o);
Using today's builder, what happens?
- A. Prints
0 x Thali ... - B. Compile error
- C.
IllegalStateException: qty must be 1-10, got 0 - D. Prints
1 x Thali ...
Answer
C. build() checks quantity before calling the private constructor, so no Order is made. It compiles because the mistake is in a value, not a type.
Interview questions
- What is the Builder pattern? A creational pattern that separates the construction of a complex object from its representation: a builder collects the parts step by step and
build()returns the finished product. - What problems does it solve? Telescoping constructors (positional, swappable arguments, too many overloads) and the JavaBeans setter problem (half-built, mutable objects, no single place to validate).
- How do you force required parameters? Put them in the builder's constructor (or the static
builder(required...)method). - Where do you validate? In
build(), before creating the product, so rules over several fields can be checked and no invalid object ever exists. - How does a builder give immutability? The product has
finalfields, no setters and a private constructor that copies values from the builder (copying collections). - What is a fluent interface? An API designed for method chaining that reads like a sentence; each step returns the builder (
return this). - What is the director? An optional class that runs a fixed sequence of builder steps (a recipe); it can drive different builders through a builder interface.
- Builder vs Abstract Factory? Abstract Factory creates a family of related objects, usually in one call each; Builder creates one complex object step by step and returns it at the end.
- Examples in Java?
HttpRequest.newBuilder(),HttpClient.newBuilder(),Locale.Builder; Lombok's@Buildergenerates builders. - Downsides? More code (a builder per product), fields duplicated in the builder, and the builder is mutable.
Glossary
| Term | Meaning, with an example |
|---|---|
| Builder pattern | GoF creational pattern: separate how an object is constructed from the finished object. Order.Builder → Order |
| Builder | The object that collects parts step by step and returns the product from build() |
| Product | The finished object the builder creates. Order |
| Director | Optional class that runs a fixed recipe of builder steps. Combos.partyPack(...) |
| Client | The code that uses the builder or the director. Main |
| Constructor | Special method that runs when an object is created with new (episode 2) |
| Constructor overloading | Several constructors with different parameter lists (episode 2) |
| Telescoping constructor anti-pattern | A chain of ever-longer constructors to cover optional parameters |
| Anti-pattern | A common solution that looks fine but causes trouble (episode 21) |
| Positional arguments | Arguments whose meaning comes only from their place in the list. false, true, null |
| JavaBeans | Naming convention: a no-argument constructor plus getX()/setX() for each field |
| JavaBeans setter problem | With setters the object exists half-built, can be changed later, and has no single place to validate |
| Mutable / immutable | Can / cannot change after creation. A String is immutable (episode 6) |
| Immutable result object | The product of a builder, with final fields and no setters |
| Static nested class | A class declared static inside another class; created without an outer object. new Order.Builder(...) |
| Required vs optional parameters | Values that must be given (builder constructor) vs values with defaults (named steps) |
| Default value | The value a field has when nobody sets it. qty = 1 |
return this |
A method returning the object it was called on, so another call can follow |
| Method chaining | Calling methods one after another on the returned object. .qty(2).extraCheese() |
| Fluent interface | An API designed for method chaining that reads like a sentence |
| Build-time validation | Checking all rules in build() before the product exists |
IllegalStateException |
Standard unchecked exception: the object is in the wrong state for this call |
| Stack trace | The list of method calls printed with an exception. at Order$Builder.build(Main.java:16) |
Order$Builder |
The JVM's name for the nested class Builder inside Order |
HttpRequest |
JDK class (java.net.http) describing a web request, created with HttpRequest.newBuilder() |
| Annotation | A @ label that the compiler or tools can read. @Override, @Builder |
| Lombok | Open-source Java library that generates repetitive code such as builders |
@Builder |
Lombok annotation that generates a builder class, chained setters, build() and builder() |
List.copyOf |
Returns an unmodifiable copy of a list (used to keep a product immutable) |
| Machine-coding round | Interview round where you write a small working design in about 1-2 hours (episode 1) |
Summary
- Big constructors make values positional, so same-type values swap silently; adding overloads gives the telescoping constructor anti-pattern.
- JavaBeans setters give names but leave the object half-built and mutable, with no single place to validate.
- A builder takes required values in its constructor, optional values as named steps that
return this(a fluent interface), andbuild()validates once, then creates an immutable product through a private constructor. - The director stores fixed recipes; the JDK (
HttpRequest.newBuilder()) and Lombok@Builderuse the same idea. - Use it for many, mostly optional parameters; use a constructor for two or three required ones.
Next episode: The Prototype and Object Pool patterns.