Notes
The problem
First attempt: telescoping constructors. One with name and format, one that also takes dates, one that adds columns and time zone, and so on, each calling the next. A caller who needs only a zip file and an email must pass nulls for everything in between. Reading new tangled export with three nulls, a true, another null and a string, nobody can tell which value is which. Two string arguments side by side are easy to swap, and the compiler cannot help.
TangledExport(name, format)
TangledExport(name, format, from, to)
TangledExport(name, format, from, to,
columns, zone)
// ... and the full one:
new TangledExport("sales", CSV, null,
null, null, "UTC", true, null,
"ops@corp.test");
// which null is which? Setters are no better
Second attempt: an empty constructor plus setters. It reads better, but it creates new problems. There is no single moment when the object is complete, so there is no good place to validate. Forget to set zipped, and the export runs with a password that means nothing. And the object stays mutable forever, so another thread or a later line can change it after you checked it.
BeanExport e = new BeanExport();
e.setName("sales");
e.setFormat(Format.CSV);
e.setPassword("s3cret");
// forgot setZipped(true)
exporter.run(e); // runs anyway
// no single moment to validate
// anyone can change it later The idea
The idea in plain words: a separate helper object collects the settings, one named method call at a time. When you are done, you call build. Build checks that everything fits together and only then creates the real object, which has no setters and cannot change. Required values go into the method that starts the builder, so you cannot forget them. Optional values each get a clearly named method.
- a helper object collects the
- settings one named call at a
- time, then build() checks them
- and creates the real object
- required: in builder(...)
- optional: named methods
- checks: inside build()
- result: immutable
The participants
The participants. Report export is the product: final fields, a private constructor, no setters. Report export dot builder is a static nested class that holds the same fields, but mutable, with sensible defaults. Format is a small enum. Export controller, the client, asks for a builder, chains a few calls, and calls build. Because the product constructor is private, the builder is the only way in.
Code: the builder
The builder holds required fields as final, set by its constructor, and optional fields with defaults, like time zone defaulting to U T C. Each option method stores a value and returns this, the builder itself. Returning this is what lets you chain the calls on one line. A date range method takes both dates together, so a caller can never set only one end of the range.
static final class Builder {
private final String name;
private final Format format;
private ZoneId zone = ZoneOffset.UTC;
private boolean zipped;
Builder zone(ZoneId z) {
this.zone = z; return this; }
Builder zipped(boolean z) {
this.zipped = z; return this; }
ReportExport build() { ... }
} Code: build() validates
Build is where validation lives, because it is the one moment when all values are known together. If the range ends before it starts, throw. If there is a password but zipped is false, throw, because a password only makes sense on a zip file. Then call the private constructor, which copies every field. The column list is copied with list copy of, so later changes to the builder cannot leak into the finished object.
ReportExport build() {
if (to != null && to.isBefore(from))
throw new IllegalStateException(
"range ends before it starts");
if (password != null && !zipped)
throw new IllegalStateException(
"password needs zipped(true)");
return new ReportExport(this);
}
// constructor: List.copyOf(columns) Run-through
Here is the client. Start with builder, passing the name and CSV. Chain the date range, two columns, zipped true, a password and an email address. Then build. Each line says what it sets, so there is nothing to guess. Leave out zipped, and build throws straight away with a clear message, before any export runs. What comes back is a finished, checked, unchangeable report export.
ReportExport job = ReportExport
.builder("weekly-sales", Format.CSV)
.dateRange(monday, sunday)
.column("region").column("revenue")
.zipped(true)
.password("s3cret")
.emailTo("ops@corp.test")
.build(); Records + builder
Since Java sixteen, records give you immutable data classes for free. Pair one with a small nested builder for names and defaults. Here, export schedule is a record with a run time, a zone and a retry count. Validation goes in the compact constructor, so it runs even if someone skips the builder, because a record's canonical constructor cannot be made more private than the record. A to builder method copies a record back into a builder, so you can change one field.
record ExportSchedule(LocalTime runAt,
ZoneId zone, int retries) {
ExportSchedule { // compact
if (retries < 0 || retries > 5)
throw new IllegalArgumentException();
}
static Builder builder() { ... }
Builder toBuilder() { ... }
}
// Builder: runAt 06:00, UTC, 2 When to use it
Use a builder when there are roughly four or more parameters and most are optional, when there are rules that involve several fields together, and when the result should be immutable and safe to share across threads. It also makes test data very readable. Avoid it for two or three required fields, where a plain constructor or a record is shorter and just as clear. A builder is extra code to keep in sync with the class.
- use when:
- • four or more parameters,
- most of them optional
- • rules across fields
- • the result must be immutable
- • a readable test fixture
- avoid when:
- • two or three required fields
- (a constructor is clearer)
Trade-offs
The costs. Every field is written twice, once in the product and once in the builder, and the two must stay in step. If you put required fields into optional methods, a missing one is only caught at runtime, so pass required values to the method that creates the builder. The builder itself is mutable, so do not share one across threads. And build should return a new object every time, so two calls never share state.
- • fields are written twice
- (product and builder)
- • required fields hidden in a
- builder are found at runtime
- -> put them in builder(..)
- • a builder is mutable: do not
- share one across threads
- • build() should return a new
- object each time
In Java
The Java standard library uses builders in several places. Http request dot new builder lets you set the address, timeout and method, then build an immutable request. Http client has one too. Locale dot builder assembles a locale from language and region. Stream dot builder collects elements, then builds a stream. String builder is builder like, a mutable buffer that produces an immutable string, though it does no validation.
- HttpRequest.newBuilder()
- .uri(..).timeout(..).GET()
- .build()
- HttpClient.newBuilder()
- new Locale.Builder()
- .setLanguage("en").build()
- Stream.builder()
- StringBuilder: a mutable
- text buffer, builder-like
Neighbours
How does it compare? Factory method and abstract factory decide which class to create, usually in a single call. Builder decides how one object is assembled, over many calls, with one check at the end. Prototype starts from a copy of an object you already have. The to builder method sits between the last two: copy an existing value into a builder, change a field, and build again.
- factory method / abstract
- factory: WHICH class, in
- one call
- builder: HOW one object is
- assembled, in many calls,
- then checked once
- prototype: start from a copy
- of an existing object
- toBuilder() mixes the two
In LLD interviews
In interviews, builders appear wherever a request has many optional parts: a booking or order request, a search query with filters, a notification with title, body, channel, priority and retries, or a customisable meal order. Interviewers like to see required fields up front, validation in build, and an immutable result. Common mistakes are a builder that checks nothing, and a product that still has setters, which defeats the point.
- booking or order requests
- search queries with filters
- notifications: title, body,
- channel, priority, retries
- pizza or meal customisation
- HTTP clients, config objects
- mistakes:
- • builder with no validation
- • setters left on the product