Java Builder Pattern: Build Complex Objects Without Telescoping Constructors

Maya's bookstore app has grown since the last post. Checkout notifies customers, regions have their own senders and footers, and the shop is selling steadily. Now Maya wants a monthly sales report: how much each category sold, in which region, above which order value — delivered as a PDF, a CSV, or a web page, to whoever needs to see it. The first version of the report request is a single constructor with seven parameters, and every call site carries a comment explaining which argument is which — because without the comment, nobody can tell. Then the shop asks for an eighth option, a minimum order count, and the comment gets longer while the constructor gets wider. The question this post asks is the one the comment is already answering: how do you build an object with many optional parts, readably?

Post 1 asked what varies? Post 2, Java Singleton Pattern: Enum, Lazy Holder & Double-Checked Locking Explained, asked how many? Post 3, Java Factory Pattern: Factory Method vs Abstract Factory With Examples, asked who decides which object gets created? This post asks a fourth question: how do you assemble one object, piece by piece, without a constructor that needs a comment? The answer is the Builder pattern. The principle for this lesson: if a constructor needs a comment to explain its arguments, it needs a builder.

1. The customer problem

Maya's requirement is plain: a sales report request must name a format — PDF, CSV, or HTML — and may narrow the report by a date range, a category, a region, and a minimum order amount, and may list who receives it. If a field is left out, the report still works: no dates means all time, no category means every category, no recipients means just Maya. When the next option arrives, adding it must not mean re-learning the order of seven arguments, and leaving one out must not mean passing null and hoping the reader knows what it means. Seven fields today, an eighth already being discussed, and every report uses a different subset of them.

Notice what she did not ask for. She did not ask for a reporting framework, a configuration file, or a new library. She asked for one property: the call site must read like the request itself — each part named, each omission obvious. Hold that thought, because "the object gets built" and "the object gets built readably" are not the same requirement, and confusing them is how a constructor grows to seven parameters with a comment taped to it. The test for everything in this post is simple: read a call site out loud, and count the words you have to explain.

2. Clarify the ask: what varies, what stays

Before writing any code, split the problem again:

  • What stays stable: the report flow — take a request, fetch the orders, filter them, format the result, deliver it. That shape will not change when the eighth option or the ninth arrives.
  • What varies: which fields a given report sets — and they vary in two ways, which is the whole design question. One field is required — the format, because a report with no format cannot be produced at all. The rest are optional, each with a sensible default: no dates means all time, no category means any category, no region means any region, no minimum amount means zero, no recipients means just Maya.

That split matters, because it is what the design must make visible. A seven-parameter constructor hides it: required and optional look identical, and "not set" is spelled null. A builder makes the split structural — the required field is impossible to forget, and every optional field carries its default in plain sight. Section 5 shows what happens when the split is not enforced: the request gets built in a state that should not exist, and the failure surfaces far from the call that caused it.

3. The minimum concept: name the parts, build in steps

The Builder pattern has four parts, and they each do one job:

  • The product — the object being built, ReportRequest. It is immutable: every field is final, there are no setters, and its constructor is private, so only the builder can create one.
  • The builder — a static nested class, ReportRequest.Builder, holding the same fields as mutable working state. It alone assembles a product.
  • Fluent setters — one method per field, each setting its field and returning the builder itself (return this), so the calls chain into one readable statement.
  • build() — the one method that checks the assembled state and creates the product. Validation lives here and only here — exactly one place where an invalid request can be refused.

It answers a different question from the Factory patterns in post 3. A factory answers which object gets created — email or SMS, US or EU. A builder answers how is this one object put together, piece by piece, when it has too many parts to name in a single constructor call.

Telescoping constructors vs the fluent builder WITHOUT A BUILDER WITH A BUILDER ReportRequest(3 args) ReportRequest(5 args) ReportRequest(7 args) "CSV", 2026-11-01, 2026-11-30, "fiction", null, 50.0, [...] Each new option adds a constructor — and only a comment at the call site says which argument is which. ReportRequest.builder() .format("CSV") .from(2026-11-01).to(2026-11-30) .category("fiction") .build() ReportRequest (immutable) Each step names itself; build() checks the result.

You have already used the fluent shape. StringBuilder in the JDK works the same way: append returns the same builder, so the calls chain — new StringBuilder().append("a").append("b").toString(). Strictly speaking, StringBuilder is not the Gang of Four Builder pattern — it builds a string, not a separate product type — but the chaining idea is identical. The full pattern adds two things StringBuilder does not need: a separate product type, and a build() step that validates before anything is created.

4. Build: from seven arguments to a fluent chain

Here is the naive version: one class, a chain of constructors that delegate to each other, each adding the next option. A report request holds a format, a date range, two filters, a minimum amount, and a list of recipients:

final class ReportRequest {
    private final String format;
    private final LocalDate start;
    private final LocalDate end;
    private final String category;
    private final String region;
    private final double minAmount;
    private final List<String> recipients;

    ReportRequest(String format, LocalDate start, LocalDate end) {
        this(format, start, end, null, null, 0.0, List.of());
    }

    ReportRequest(String format, LocalDate start, LocalDate end,
                  String category, String region) {
        this(format, start, end, category, region, 0.0, List.of());
    }

    ReportRequest(String format, LocalDate start, LocalDate end,
                  String category, String region,
                  double minAmount, List<String> recipients) {
        this.format = format;
        this.start = start;
        this.end = end;
        this.category = category;
        this.region = region;
        this.minAmount = minAmount;
        this.recipients = recipients;
    }
}

This is the telescoping pattern, and it works — for a while. The costs are three, and they all grow with the next option. First, argument order is the API: swap the two strings, category and region, and the code still compiles, because both are String. Second, null is doing a job it was never given: at the call site, null means "no region filter," but only by convention — nothing in the code says so. Third, every new option adds a constructor: the eighth option means a fourth constructor, and every caller must find the right rung of the ladder. Here is the call site, comment and all:

// format, start, end, category, region, minAmount, recipients
ReportRequest request = new ReportRequest(
        "CSV", LocalDate.of(2026, 11, 1), LocalDate.of(2026, 11, 30),
        "fiction", null, 50.0, List.of("maya@books.example"));

Read that call out loud. Without the comment, which argument is "fiction" — the category, or the region? Which null is the region, and which would be the category? The comment knows. The code does not. That is the smell the principle names: the constructor needs a comment to explain its arguments, so it needs a builder.

The builder fix has three moves: make the product's constructor private, give the builder one fluent method per field, and let build() assemble the product. Here is the first working version — readable, but deliberately trusting the caller, because section 5 is about what that trust costs:

final class ReportRequest {
    private final String format;
    private final LocalDate start;
    private final LocalDate end;
    private final String category;
    private final String region;
    private final double minAmount;
    private final List<String> recipients;

    private ReportRequest(Builder builder) {
        this.format = builder.format;
        this.start = builder.start;
        this.end = builder.end;
        this.category = builder.category;
        this.region = builder.region;
        this.minAmount = builder.minAmount;
        this.recipients = builder.recipients;
    }

    static Builder builder() {
        return new Builder();
    }

    static final class Builder {
        private String format;
        private LocalDate start;
        private LocalDate end;
        private String category;
        private String region;
        private double minAmount;
        private List<String> recipients = new ArrayList<>();

        Builder format(String format) {
            this.format = format;
            return this;
        }

        Builder from(LocalDate start) {
            this.start = start;
            return this;
        }

        Builder to(LocalDate end) {
            this.end = end;
            return this;
        }

        Builder category(String category) {
            this.category = category;
            return this;
        }

        Builder region(String region) {
            this.region = region;
            return this;
        }

        Builder minAmount(double minAmount) {
            this.minAmount = minAmount;
            return this;
        }

        Builder recipient(String recipient) {
            recipients.add(recipient);
            return this;
        }

        Builder recipients(List<String> recipients) {
            this.recipients = recipients;
            return this;
        }

        ReportRequest build() {
            return new ReportRequest(this);
        }
    }

    String describe() {
        String period = (start == null || end == null)
                ? "all time" : start + ".." + end;
        return "Report request: format=" + format
                + ", period=" + period
                + ", category=" + (category == null ? "any" : category)
                + ", region=" + (region == null ? "any" : region)
                + ", minAmount=" + minAmount
                + ", recipients=" + recipients;
    }
}

Two details make the chain work. Every setter returns this — the builder itself — so each call hands the same builder to the next, and the statement reads like a list of choices. And the product's constructor is private and takes the builder, not seven arguments: the only way to obtain a ReportRequest is through the builder, which makes it the only place construction can be controlled. Here is the same request as before, built fluently:

public class BuilderDemo {
    public static void main(String[] args) {
        ReportRequest request = ReportRequest.builder()
                .format("CSV")
                .from(LocalDate.of(2026, 11, 1))
                .to(LocalDate.of(2026, 11, 30))
                .category("fiction")
                .minAmount(50.0)
                .recipient("maya@books.example")
                .build();
        System.out.println(request.describe());
    }
}
Report request: format=CSV, period=2026-11-01..2026-11-30, category=fiction, region=any, minAmount=50.0, recipients=[maya@books.example]

Read that call site out loud now. Every argument names itself — format, from, to, category, minAmount, recipient — and the ones left out are simply absent, not null. The region was never set, and the output says so: region=any. The order of the calls does not matter, because each setter names its own field. And adding the eighth option means adding one setter — not a fourth constructor, and not a new comment at every call site.

5. Break it: the request that should not exist

The builder made construction readable. Readable is not the same as correct — and this version trusts the caller completely. build() assembles whatever it was given, with no questions asked. Here is the first way that trust breaks. A report with the dates the wrong way round is meaningless — an end before a start covers no days at all — but nothing stops it being built:

ReportRequest broken = ReportRequest.builder()
        .format("CSV")
        .from(LocalDate.of(2026, 11, 30))
        .to(LocalDate.of(2026, 11, 1))
        .build();
System.out.println(broken.describe());
Report request: format=CSV, period=2026-11-30..2026-11-01, category=any, region=any, minAmount=0.0, recipients=[]

The object exists, it prints cleanly, and it is wrong: a period that ends before it starts. The failure surfaces later and further away — the report engine runs the query, finds no orders in an empty range, and delivers an empty report, and nobody knows whether November really had no fiction sales or the request was broken. The same hole admits a request with no format at all: build() with no .format(...) call produces a request whose describe() prints format=null, and the engine fails only when it tries to pick a renderer. In both cases the mistake was made at the call site and discovered somewhere else entirely — and that distance is what validation at build() time is for.

Now the second break, which is subtler, because the object looks immutable. The fields are all final and there are no setters — but look again at the two lines that move the recipient list from the caller to the product. The recipients(List) setter stores the caller's list, and the product's constructor stores the builder's list. No copy is made anywhere, so all three — the caller's list, the builder's list, and the product's list — are the same list:

List<String> team = new ArrayList<>();
team.add("maya@books.example");
ReportRequest request = ReportRequest.builder()
        .format("PDF")
        .recipients(team)
        .build();
team.add("someone-else@books.example"); // after build()
System.out.println(request.describe());
Report request: format=PDF, period=all time, category=any, region=any, minAmount=0.0, recipients=[maya@books.example, someone-else@books.example]

The "immutable" request changed after it was built. A report addressed to Maya alone now goes to someone else too, and the code that added the second name never touched the request — it only touched its own list. final stopped the reference from being reassigned; it never stopped the list itself from changing. That is the classic aliasing trap, and it is why "immutable" has to mean more than "the fields are final" — the product must own its data, not borrow it from the caller.

6. Harden it: validate at build() time, copy at both boundaries

Both breaks have the same fix shape: the builder is the single gate, so the gate does the work. First, validation — build() checks everything that can be wrong, in one place, before any product exists:

ReportRequest build() {
    if (format == null) {
        throw new IllegalStateException("format is required");
    }
    if (!format.equals("PDF") && !format.equals("CSV")
            && !format.equals("HTML")) {
        throw new IllegalArgumentException("Unknown format: " + format);
    }
    if (start != null && end != null && end.isBefore(start)) {
        throw new IllegalArgumentException(
                "End date must not be before start date");
    }
    if (minAmount < 0) {
        throw new IllegalArgumentException(
                "minAmount must not be negative");
    }
    return new ReportRequest(this);
}

Three things to notice. First, the order matters: the null check on format comes before the value check, because calling format.equals(...) on a null format would throw a NullPointerException instead of the intended error. Second, a single date is allowed — an open-ended range is legitimate — and only an end before a start is refused. That is a product decision, stated in the code, not an oversight. Third, the exception types say what went wrong: IllegalStateException for a missing required field, IllegalArgumentException for a present-but-illegal value.

Second, the copies. The aliasing break is fixed at both boundaries, and both are needed:

// In the builder: copy on the way in, so the caller's list
// can never reach the builder.
Builder recipients(List<String> recipients) {
    this.recipients.addAll(recipients);
    return this;
}

// In the product's constructor: copy on the way out, so the
// builder's list can never reach the product.
private ReportRequest(Builder builder) {
    ...
    this.recipients = List.copyOf(builder.recipients);
}

Why both? Copying on the way in protects the builder from the caller: if the caller mutates their list after calling recipients(...), the builder's copy is untouched. Copying on the way out protects the product from the builder: the same builder can now safely build a second request, because build() snapshots the state instead of sharing it. And List.copyOf makes the product's list unmodifiable. That is what "immutable" actually means here: final fields, no setters, and no shared mutable state anywhere in the chain.

Required versus optional, once more, as a list. Everything the builder knows falls into one of two buckets:

  • Required — format. build() throws IllegalStateException if it is missing, and IllegalArgumentException if it is not PDF, CSV, or HTML.
  • Optional — everything else, each with a default. No dates means all time; a single date means an open-ended range. No category or region means any. No minimum amount means 0.0, and a negative one is refused. No recipients means an empty list. Nothing optional can be forgotten into an invalid state, because the default is the valid state.

When not to use a builder. A builder is a whole extra class, and sometimes that is more machinery than the problem deserves. As a rule of thumb — not a law — reach for a plain constructor, or a record, when the object has two or three fields, all of them required, and no meaningful defaults: there is nothing to make optional, so there is nothing for the builder to do. Skip it too when the object is genuinely mutable by design — a settings object the application updates over its lifetime is not a snapshot, and forcing it through a builder buys nothing. The builder earns its keep when the fields are many, the combinations are many, and most of them have defaults — exactly the shape of this report request.

A note on Lombok @Builder and records. Two alternatives you will meet in real codebases, worth naming without taking a side. A Java record is an excellent immutable data carrier — compact, with equals, hashCode, and toString generated — but its canonical constructor takes every component at once, so a record with seven components has the same call-site readability problem this post started with; a hand-written builder inside a record is a legitimate combination. Lombok's @Builder generates the same shape this post builds by hand — builder class, fluent setters, build() method — which is why this lesson builds it by hand first: know what the annotation generates before you let it generate it. Whether to add Lombok as a dependency is a team decision about annotation processing and tooling; this lesson does not use it, and recommends neither for nor against it.

Verify with explicit checks, not assertions — the same discipline as posts 1 and 3. Assertions can be switched off at runtime, so they are documentation, not a safety net. A small check program that builds a valid request and three invalid ones — missing format, unknown format, end before start — throws on mismatch, whether or not assertions are enabled. It is the check that would have caught the section 5 inverted range before an empty report reached Maya.

7. Communicate: explain it to a human

The code is only half the job. Here is how you explain this change to Maya, without jargon:

"Before, asking for a report meant filling in seven blanks in the right order — format, dates, category, region, amount, recipients — and only a comment said which blank was which. Mix two of them up and the report came out wrong, with nothing complaining. Now, asking for a report reads like the request itself: format PDF, November, fiction, orders over fifty, send it to me. You mention only the parts you care about; the rest sensibly default. And the request is checked the moment you make it — a missing format or an end date before the start is refused immediately, with a clear message, instead of turning into an empty report later. The one trade-off: this is a snapshot — once made, a request can't be changed, which is what makes it safe to pass around, but a correction needs a new request, not an edit to the old one."

If she understands that paragraph, she understands the design — and she can approve the next change with confidence, because she knows exactly what "each part names itself" guarantees and what it costs.

Field check

Six rules to carry into the rest of the track:

  1. If a constructor needs a comment to explain its arguments, it needs a builder. The comment is the design telling you the call site is unreadable — listen to it.
  2. The builder owns the assembly; the product owns the result. Fluent setters return the builder; build() returns the product. The product's constructor is private, so the builder is the only way in.
  3. Validate at build() time. Required fields, legal values, and rules between fields — end not before start — are all checked in one place, before any product exists.
  4. Copy at both boundaries. The builder copies what the caller passes in; the product copies what the builder holds. A built object must not change when the caller changes their list.
  5. Make the built object immutable. Final fields, no setters, unmodifiable collections — so a request means the same thing everywhere it travels.
  6. No builder without a reason. Few fields, all required, is a constructor or a record. A pattern is a tool, not a goal.

Previous in this track: Java Factory Pattern: Factory Method vs Abstract Factory With Examples · Continue: Java Learning Roadmap 2026

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

30 Core Java Basic Interview Questions for Freshers