LOW-LEVEL DESIGN · CREATIONAL PATTERNS · CREATIONAL · 25 OF 48

Builder Pattern in Java: Many Optional Fields, One Immutable Object

The Builder pattern with a report export request: why telescoping constructors and setter-based objects break down, a fluent builder with required fields up front, an immutable result, validation in build(), a record with a nested builder and toBuilder, and how it differs from factories, with examples from the Java standard library.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 185 lines, with a small main() demo. Save it as ReportExportBuilderDemo.java, then run javac ReportExportBuilderDemo.java && java ReportExportBuilderDemo.

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/** Builder with a report export request: readable creation, validation in build(), immutable result. */
public class ReportExportBuilderDemo {

    enum Format { CSV, XLSX, PDF }

    // ---------- the problem: telescoping constructors (only the longest one shown) ----------
    static final class TangledExport {
        final String summary;

        TangledExport(String name, Format format, LocalDate from, LocalDate to, List<String> columns,
                      String zone, boolean zipped, String password, String notifyEmail) {
            // Callers write:
            //   new TangledExport("sales", CSV, null, null, null, "UTC", true, null, "ops@corp.test")
            this.summary = name + "/" + format + "/zip=" + zipped + "/to=" + notifyEmail;
        }
    }

    // ---------- the clean version: an immutable product with a nested builder ----------
    static final class ReportExport {
        private final String name;
        private final Format format;
        private final LocalDate from;
        private final LocalDate to;
        private final List<String> columns;
        private final ZoneId zone;
        private final boolean zipped;
        private final String password;
        private final String notifyEmail;

        private ReportExport(Builder b) {        // only the builder can call this
            this.name = b.name;
            this.format = b.format;
            this.from = b.from;
            this.to = b.to;
            this.columns = List.copyOf(b.columns);   // defensive copy: builder changes cannot leak in
            this.zone = b.zone;
            this.zipped = b.zipped;
            this.password = b.password;
            this.notifyEmail = b.notifyEmail;
        }

        /** Required values go here, so the compiler makes callers supply them. */
        static Builder builder(String name, Format format) {
            return new Builder(name, format);
        }

        @Override
        public String toString() {
            String range = from == null ? "all time" : from + ".." + to;
            return name + "." + format.name().toLowerCase() + (zipped ? ".zip" : "") + " [" + range + ", "
                    + (columns.isEmpty() ? "all columns" : columns) + ", " + zone
                    + (password != null ? ", locked" : "")
                    + (notifyEmail != null ? ", mail " + notifyEmail : "")
                    + "]";
        }

        static final class Builder {
            private final String name;
            private final Format format;
            private LocalDate from;
            private LocalDate to;
            private final List<String> columns = new ArrayList<>();
            private ZoneId zone = ZoneOffset.UTC;   // sensible default
            private boolean zipped;
            private String password;
            private String notifyEmail;

            private Builder(String name, Format format) {
                this.name = Objects.requireNonNull(name, "name");
                this.format = Objects.requireNonNull(format, "format");
            }

            Builder dateRange(LocalDate from, LocalDate to) {   // both ends together, never one
                this.from = Objects.requireNonNull(from);
                this.to = Objects.requireNonNull(to);
                return this;
            }

            Builder column(String column) {
                columns.add(column);
                return this;
            }

            Builder zone(ZoneId zone) {
                this.zone = Objects.requireNonNull(zone);
                return this;
            }

            Builder zipped(boolean zipped) {
                this.zipped = zipped;
                return this;
            }

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

            Builder emailTo(String email) {
                this.notifyEmail = email;
                return this;
            }

            /** The single gate: rules that involve several fields are checked here. */
            ReportExport build() {
                if (from != null && to.isBefore(from)) {
                    throw new IllegalStateException("date range ends before it starts");
                }
                if (password != null && !zipped) {
                    throw new IllegalStateException("a password needs zipped(true)");
                }
                return new ReportExport(this);
            }
        }
    }

    // ---------- record + builder ----------
    record ExportSchedule(LocalTime runAt, ZoneId zone, int retries) {
        ExportSchedule {                         // compact constructor: runs even without the builder
            Objects.requireNonNull(runAt, "runAt");
            Objects.requireNonNull(zone, "zone");
            if (retries < 0 || retries > 5) {
                throw new IllegalArgumentException("retries must be 0 to 5");
            }
        }

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

        Builder toBuilder() {                    // copy this value into a builder to change a field
            return new Builder().runAt(runAt).zone(zone).retries(retries);
        }

        static final class Builder {
            private LocalTime runAt = LocalTime.of(6, 0);
            private ZoneId zone = ZoneOffset.UTC;
            private int retries = 2;

            Builder runAt(LocalTime runAt) { this.runAt = runAt; return this; }

            Builder zone(ZoneId zone) { this.zone = zone; return this; }

            Builder retries(int retries) { this.retries = retries; return this; }

            ExportSchedule build() { return new ExportSchedule(runAt, zone, retries); }
        }
    }

    public static void main(String[] args) {
        TangledExport old = new TangledExport("sales", Format.CSV, null, null, null, "UTC", true, null,
                "ops@corp.test");
        System.out.println("Telescoping: " + old.summary + "   (which null was which?)");

        LocalDate monday = LocalDate.of(2026, 3, 2);
        ReportExport weekly = ReportExport.builder("weekly-sales", Format.CSV)
                .dateRange(monday, monday.plusDays(6))
                .column("region").column("revenue")
                .zone(ZoneId.of("Asia/Kolkata"))
                .zipped(true)
                .password("s3cret")
                .emailTo("ops@corp.test")
                .build();
        System.out.println("Built: " + weekly);
        System.out.println("Minimal: " + ReportExport.builder("stock", Format.XLSX).build());

        try {
            ReportExport.builder("payroll", Format.PDF).password("s3cret").build();
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        ExportSchedule daily = ExportSchedule.builder().retries(3).build();
        ExportSchedule evening = daily.toBuilder().runAt(LocalTime.of(18, 30)).build();
        System.out.println("Schedules: " + daily + " / " + evening);
    }
}

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.

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

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

Builder in plain words
  • 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.

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

build()
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.

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

ExportSchedule
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 or avoid
  • 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.

Costs and gotchas
  • • 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.

Where you see it
  • 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.

How it differs
  • 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.

Where it comes up
  • 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

Interview questions

What problem does the builder pattern solve?

It replaces long constructors with many optional and same-typed parameters, which are hard to read and easy to misuse. Named methods make each value clear, and a final build() step validates the full set and returns an immutable object.

What is the telescoping constructor problem?

A class offers a chain of constructors with more and more parameters, each calling the next. Callers must pass nulls or defaults for options they do not need, the meaning of each position is unclear, and two arguments of the same type can be swapped without a compiler error.

Why not just use setters?

With setters the object is mutable and can be used before it is complete, and there is no single point where all fields are known together to validate them. A builder keeps the mutable phase inside the builder and hands out only a finished, checked, immutable object.

Where should validation go in a builder?

In build(), or in the product constructor that build() calls, because that is when all values are known together and cross-field rules can be checked. Individual setter methods can check single values, such as a non-null argument, but rules that span fields belong in build().

How do you handle required fields in a builder?

Pass them to the static method or constructor that creates the builder, for example builder(name, format). Then the compiler forces callers to provide them, instead of discovering a missing value only when build() runs.

How do builders work with Java records?

A record already gives an immutable class with a canonical constructor. Add a static nested Builder with defaults and named methods whose build() calls that constructor, and put validation in a compact constructor so it runs even when the builder is bypassed. A toBuilder() method helps create modified copies.

Is a builder thread safe?

Usually not; it is a mutable helper meant to be used by one thread and then thrown away. The object it builds, however, should be immutable, which makes the result safe to share between threads without locks.

Name builders in the Java standard library.

java.net.http.HttpRequest.newBuilder() and HttpClient.newBuilder(), Locale.Builder, and Stream.builder() are all builders. StringBuilder is a related idea: a mutable buffer you append to and then turn into an immutable String.