LLD

Creational Patterns

Builder pattern

Some objects have three values they must have and eight they might. We build a flight search request twice, once with constructors that keep growing and once with the Builder pattern, and look at what each version costs.

A flight search form asks for three things: where from, where to, and when. Then it offers more that you may or may not touch: a return date, the number of adults, children and infants, the cabin, non-stop only, a price limit and preferred airlines. Most searches change only a few of them. Every search still has to become one object that the rest of the system can trust.

The same shape shows up in many places. An HTTP request has a URL, and maybe headers, a body and a timeout. A notification has a recipient and a message, and maybe a template, a priority and a send time. A database query has a table, and maybe filters, a sort order and a page size. Each one has a few required values, many optional ones, and rules that tie the values together.

The Builder pattern gives such an object a helper that collects the values one at a time and then creates the object in one step. In this article we build a flight search request twice: first with constructors, then with a builder. Then we look at what the builder costs, when a plain record is better, how a builder differs from a factory, and how this shows up in interviews.

All the code is Java, and all of it compiles and runs. The snippets come from two complete projects, the first version and the finished one, apart from two short sketches that are labelled. The Open file button on a snippet from the finished project shows the whole file in a code browser.

The search we are building

A search has three required values and eight optional ones. It must meet these requirements:

  1. Required values. A search has a from airport, a to airport and a departure date. It cannot exist without them.
  2. Optional values with defaults. A return date (none means one way), adults (1), children (0), infants (0), cabin (economy), non-stop only (no), a price limit (none) and preferred airlines (any).
  3. Seven rules. From and to must differ. The return date cannot be before the departure date. At least one adult travels. No passenger count is negative. Each infant sits on an adult's lap, so there can be no more infants than adults. A booking has at most nine seats, counting adults and children. A price limit must be more than $0.
  4. Every broken rule is reported at once, so the form can mark all the wrong fields together.
  5. A finished search never changes. The results page keeps searches as the keys of a cache, and builds new searches when the user moves the date.
A flight search, part by part
The three required values must be given. The eight optional ones (dashed) start at a default. The rules (amber) are checked once every value is in, because four of them read more than one value. Then the search is built as a FlightSearch that never changes (white), or every broken rule comes back together in one InvalidSearchException (red).The three required values must be given. The eight optional ones (dashed) start at a default. The rules (amber) are checked once every value is in, because four of them read more than one value. Then the search is built as a FlightSearch that never changes (white), or every broken rule comes back together in one InvalidSearchException (red).
Three values are required, eight have defaults, and seven rules decide whether the search is valid. The three required values must be given. The eight optional ones (dashed) start at a default. The rules (amber) are checked once every value is in, because four of them read more than one value. Then the search is built as a FlightSearch that never changes (white), or every broken rule comes back together in one InvalidSearchException (red).

The figure separates three things a constructor mixes together: what must be given, what has a default, and which rules decide whether the values make sense together. Most of the design follows from that split. In an interview it is the first thing to write down, before any class.

The first version: constructors that keep growing

The usual first answer is one constructor per common case, each calling the next one with a default filled in. This shape is called a telescoping constructor:

FlightSearch.javalines 17–43 of 100
    public FlightSearch(Airport from, Airport to, LocalDate departure) {        this(from, to, departure, null);    }     public FlightSearch(Airport from, Airport to, LocalDate departure, LocalDate returnDate) {        this(from, to, departure, returnDate, 1, 0, 0);    }     public FlightSearch(Airport from, Airport to, LocalDate departure, LocalDate returnDate,                        int adults, int children, int infants) {        this(from, to, departure, returnDate, adults, children, infants, CabinClass.ECONOMY);    }     public FlightSearch(Airport from, Airport to, LocalDate departure, LocalDate returnDate,                        int adults, int children, int infants, CabinClass cabin) {        this(from, to, departure, returnDate, adults, children, infants, cabin, false, null, Set.of());    }     public FlightSearch(Airport from, Airport to, LocalDate departure, LocalDate returnDate,                        int adults, int children, int infants, CabinClass cabin,                        boolean nonStopOnly, Integer maxPrice, Set<String> preferredAirlines) {        if (from.equals(to)) {            throw new IllegalArgumentException("From and to are the same airport");        }        if (infants > adults) {            throw new IllegalArgumentException("More infants than adults");        }

Every call ends up in the last constructor, which takes all eleven values. Here are two calls a results page might make:

Main.javalines 12–17 of 31
        // Two adults, one child, no infants. Which number is which?        FlightSearch family = new FlightSearch(blr, del, dec20, null, 2, 1, 0,                CabinClass.ECONOMY, true, 2_000, Set.of("6E", "AI"));        // The same call with the child and the infant swapped. It compiles.        FlightSearch swapped = new FlightSearch(blr, del, dec20, null, 2, 0, 1,                CabinClass.ECONOMY, true, 2_000, Set.of("6E", "AI"));

The second call has the child and the infant swapped. Both are int, they sit at positions six and seven in a list of eleven, and the compiler accepts the swap. The first version's demo prints what each search ended up with:

$ java Main
family:  children 1, infants 0
swapped: children 0, infants 1
cached results for the changed request: null
entries still in the cache: 1

The first two lines show the swap: the family wanted a child seat and got an infant on a lap. The last two lines come from the setter version of the first design, which we look at in a moment.

This code works, and for an object with three or four values it would be fine. The trouble is the number of values and their types.

Call sites are unreadable. 2, 1, 0, CabinClass.ECONOMY, true, 2_000 is six values with no names. A reader has to count commas to know which one is the price.

Values of the same type swap silently. Adults, children and infants are three ints in a row. From and to are two Airports in a row. A swap compiles and runs.

Every new filter means another constructor or a longer one. Adding "baggage included" either adds a twelfth parameter to the longest constructor, which breaks every call that uses it, or adds yet another constructor.

Rules are checked one at a time. The long constructor throws at the first broken rule (lines 38 to 43), so a form with three mistakes shows them one per submit. It also checks only two of the seven rules.

Eleven values in a row
On the left, each shorter constructor calls the next with defaults until the call reaches the one that takes all eleven values. On the right is a real call, with each argument numbered by position. Positions 5, 6 and 7 are three ints in a row (amber): swapping any two still compiles.On the left, each shorter constructor calls the next with defaults until the call reaches the one that takes all eleven values. On the right is a real call, with each argument numbered by position. Positions 5, 6 and 7 are three ints in a row (amber): swapping any two still compiles.
Each constructor adds a few values. The last one takes all eleven, by position. On the left, each shorter constructor calls the next with defaults until the call reaches the one that takes all eleven values. On the right is a real call, with each argument numbered by position. Positions 5, 6 and 7 are three ints in a row (amber): swapping any two still compiles.

The other common first answer is an object with setters:

SearchRequest.javalines 4–29 of 49
public class SearchRequest {    private Airport from;    private Airport to;    private LocalDate departure;    private int adults = 1;    private int infants = 0;     public void setFrom(Airport from) {        this.from = from;    }     public void setTo(Airport to) {        this.to = to;    }     public void setDeparture(LocalDate departure) {        this.departure = departure;    }     public void setAdults(int adults) {        this.adults = adults;    }     public void setInfants(int infants) {        this.infants = infants;    }

Setters fix the naming problem, because setInfants(1) says what it sets. They bring two new problems. The object exists before it is complete. Between new SearchRequest() and the last setter call, any code holding the request sees a search with no destination. And it can change after it has been used. This part of the first version's demo puts a request in a HashMap, then changes its date:

Main.javalines 21–29 of 31
        SearchRequest request = new SearchRequest();        request.setFrom(blr);        request.setTo(del);        request.setDeparture(dec20);        Map<SearchRequest, String> cache = new HashMap<>();        cache.put(request, "4 flights");        request.setDeparture(dec20.plusDays(1));        System.out.println("cached results for the changed request: " + cache.get(request));        System.out.println("entries still in the cache: " + cache.size());

The output above shows the result. The changed request now has a different hash code, so the map looks in the wrong place and finds nothing. The old entry is still in the map, and no lookup can reach it unless the date is changed back.

The idea

The Builder pattern splits the job between two classes:

  • A second class, the builder, holds the values while they are being chosen. It starts with the required values, and with the defaults for everything else.
  • Each optional value has its own named method on the builder, such as infants(1). Each method returns the builder, so calls chain one after another.
  • One method, build(), creates the finished object from everything the builder holds. The finished object's constructor is private, so build() is the only way to make one.
  • The finished object checks every rule as it is created and has no setters. Once built, it never changes.

The class that gets built is the product. In Java the builder is usually a static nested class inside the product. Being nested is what lets it call the product's private constructor.

The pattern also has an older form. A builder interface lists the steps, several builders implement those steps to produce different results, and a separate director class calls the steps in order. A trip director might call addFlight, addHotel and addTransfer, once on a PDF builder and once on an email builder. That form fits when one fixed sequence of steps must produce several different products. Our search has one product and many optional values, so a single builder with chained methods is the better fit.

Building it, step by step

Step 1: a product with only one way in

The product, FlightSearch, has a final field for every value and a private constructor that takes a builder:

search/FlightSearch.javalines 14–47 of 271
public final class FlightSearch {    public static final int MAX_SEATS = 9;     private final Airport from;    private final Airport to;    private final LocalDate departure;    private final LocalDate returnDate;    private final int adults;    private final int children;    private final int infants;    private final CabinClass cabin;    private final boolean nonStopOnly;    private final Integer maxPrice;    private final Set<String> preferredAirlines;     private FlightSearch(Builder builder) {        this.from = builder.from;        this.to = builder.to;        this.departure = builder.departure;        this.returnDate = builder.returnDate;        this.adults = builder.adults;        this.children = builder.children;        this.infants = builder.infants;        this.cabin = builder.cabin;        this.nonStopOnly = builder.nonStopOnly;        this.maxPrice = builder.maxPrice;        this.preferredAirlines = Collections.unmodifiableSet(new TreeSet<>(builder.preferredAirlines));         // The rules read the final fields, so they check exactly what this search keeps.        List<String> problems = problems();        if (!problems.isEmpty()) {            throw new InvalidSearchException(problems);        }    }

Every field is final and there are no setters, so nothing can change once the constructor returns. Line 40 copies the builder's airline set into a new sorted set and wraps it so that it cannot be changed. Without the copy, the product and the builder would share one set, and adding an airline to the builder later would change a search that was already built. Lines 43 to 46 check the rules, which we come to in Step 4.

Decision

A final class, or a record?

A record

A record gives equals, hashCode and toString without writing them. But its constructor is public and takes every value in order, eleven of them here. Any code can call it and skip the builder, which brings back the swapped ints. A compact constructor could still check the rules, so every object would stay valid, but the call would be hard to read.

A final class with a private constructorOur pick

The only way to get a FlightSearch is through build(). The accessors can return Optional<LocalDate> for the return date and OptionalInt for the price limit, which says plainly that they may be missing. The cost is that we write equals, hashCode and toString by hand, and must keep them in step with the fields.

Step 2: the builder starts with what is required

search/FlightSearch.javalines 194–211 of 271
    public static final class Builder {        private final Airport from;        private final Airport to;        private LocalDate departure;        private LocalDate returnDate;        private int adults = 1;        private int children = 0;        private int infants = 0;        private CabinClass cabin = CabinClass.ECONOMY;        private boolean nonStopOnly = false;        private Integer maxPrice;        private final Set<String> preferredAirlines = new LinkedHashSet<>();         public Builder(Airport from, Airport to, LocalDate departure) {            this.from = Objects.requireNonNull(from, "from");            this.to = Objects.requireNonNull(to, "to");            this.departure = Objects.requireNonNull(departure, "departure");        }

The three required values go into the builder's constructor. Code cannot create a builder without them, so it cannot build a search without them, and the compiler enforces this. Everything else starts at its default: one adult, economy, no price limit, any airline.

A null here is a mistake in our own code, not in the form, so it fails at once. Objects.requireNonNull throws a NullPointerException that names the missing value, instead of a confusing failure much later.

Decision

Where do the required values go?

Setters, checked in build()

The builder gets from(…), to(…) and on(…) methods like every other value, and build() refuses a search that lacks them. Every value then looks the same at the call site, but a forgotten value is only found when the program runs.

The builder's constructorOur pick

A missing value does not compile. The weakness is that from and to are both Airport, so the constructor call can still swap them. A list of three is short enough to read. With many required values, this choice would bring back the problem we started with.

A step builder

FlightSearch.from(BLR).to(DEL).on(date), where each step returns a different type that offers only the next step. Nothing can be skipped or swapped, but it takes one small interface per required value. It is worth it when there are many required values of the same type.

Step 3: one named method per optional value

search/FlightSearch.javalines 228–265 of 271
        public Builder adults(int count) {            this.adults = count;            return this;        }         public Builder children(int count) {            this.children = count;            return this;        }         public Builder infants(int count) {            this.infants = count;            return this;        }         public Builder cabin(CabinClass cabin) {            this.cabin = Objects.requireNonNull(cabin, "cabin");            return this;        }         public Builder nonStopOnly(boolean nonStopOnly) {            this.nonStopOnly = nonStopOnly;            return this;        }         public Builder maxPrice(int dollars) {            this.maxPrice = dollars;            return this;        }         public Builder preferAirline(String code) {            Objects.requireNonNull(code, "code");            if (!code.matches("[A-Z0-9]{2}")) {                throw new IllegalArgumentException("Not an airline code: " + code);            }            preferredAirlines.add(code);            return this;        }

Each method changes one value and returns this, the builder itself, so calls chain. The family search from the first version now reads like the form it came from:

demo/Main.javalines 27–36 of 97
        FlightSearch family = new FlightSearch.Builder(BLR, DEL, DEC_20)                .returningOn(DEC_20.plusDays(7))                .adults(2)                .children(1)                .infants(1)                .nonStopOnly(true)                .maxPrice(2_000)                .preferAirline("6E")                .preferAirline("AI")                .build();

Look at what these methods do not check. adults(0) and maxPrice(-5) are accepted here and refused later, all in one place. Step 4 explains why. Apart from the null checks, the one exception is preferAirline, on lines 258 to 264. Airline codes come from a fixed list of checkboxes, so a code like "6e" can only come from a bug in our code. It fails at once with an IllegalArgumentException.

Step 4: every rule is checked, and every problem reported

search/FlightSearch.javalines 49–73 of 271
    private List<String> problems() {        List<String> problems = new ArrayList<>();        if (from.equals(to)) {            problems.add("From and to are the same airport");        }        if (returnDate != null && returnDate.isBefore(departure)) {            problems.add("The return date is before the departure date");        }        if (adults < 1) {            problems.add("At least one adult must travel");        }        if (children < 0 || infants < 0) {            problems.add("Passenger counts cannot be negative");        }        if (adults >= 1 && infants > adults) {            problems.add("More infants (" + infants + ") than adults (" + adults + "): each infant sits on an adult's lap");        }        if ((long) adults + children > MAX_SEATS) {            problems.add("At most " + MAX_SEATS + " seats per booking");        }        if (maxPrice != null && maxPrice <= 0) {            problems.add("The price limit must be more than $0");        }        return problems;    }

problems() runs every rule and adds a message for each one that fails. The product's constructor (lines 43 to 46, in Step 1) throws one InvalidSearchException that carries the whole list. The demo's third search breaks three rules at once and gets three messages back.

The rules sit here, not in the builder's setter methods, because most of them read more than one value. infants(2) cannot know how many adults there will be, since adults(…) may be called after it. Only when every value is in can a rule like line 63 give the right answer. That line also skips the infant rule when the adult count is already wrong, so adults(-1) gives one problem, not two.

Line 66 adds adults and children as a long. With an int, adults(Integer.MAX_VALUE) plus one child would wrap round to a large negative number, and the nine-seat rule would pass it.

The rules read the product's final fields, not the builder's, so the check is about exactly what the search stores. The builder is not thread-safe; one thread fills it in.

Decision

Stop at the first broken rule, or report them all?

Throw at the first one

This is the simplest code: each rule throws as it fails. The person filling in the form then fixes one mistake per submit, and may hit three submits for three mistakes.

Collect every problem, then throw onceOur pick

The form shows everything that is wrong together. The exception's problems() method returns the list of messages, ready to show. This also splits the errors into two kinds. A broken rule is a person's mistake in the form, and comes back as a list to show them. A null or a malformed airline code is a mistake in our code, and fails at once.

Step 5: changing a search without changing it

The results page shows prices for the days around the chosen date. Each day needs its own search, almost the same as the user's. toBuilder() copies a search into a new builder, which can then be changed and built again:

search/FlightSearch.javalines 123–140 of 271
    public Builder toBuilder() {        Builder builder = new Builder(from, to, departure)                .adults(adults)                .children(children)                .infants(infants)                .cabin(cabin)                .nonStopOnly(nonStopOnly);        if (returnDate != null) {            builder.returningOn(returnDate);        }        if (maxPrice != null) {            builder.maxPrice(maxPrice);        }        for (String airline : preferredAirlines) {            builder.preferAirline(airline);        }        return builder;    }

The demo's date strip uses it once per day:

demo/Main.javalines 53–62 of 97
        for (int shift = -1; shift <= 1; shift++) {            FlightSearch nearby = family.toBuilder()                    .departingOn(DEC_20.plusDays(shift))                    .returningOn(DEC_20.plusDays(7 + shift))                    .build();            List<Flight> flights = service.search(nearby);            String cheapest = flights.isEmpty() ? "no flights" : "from $" + flights.get(0).pricePerSeat() + " a seat";            System.out.println("   " + nearby.departure() + ": " + cheapest);        }        System.out.println("   the original still leaves on " + family.departure());

The original search never changes, because toBuilder() gives a new builder and build() gives a new search. The demo prints the original's date at the end to show this. One change toBuilder() cannot make is swapping the airports: from and to are fixed in the builder, with no methods to change them. A search for the way back starts a new builder.

Decision

Can a builder be used again after build()?

No, one builder makes one object

build() marks the builder as used, and a second call throws. This rules out any surprise from shared state, at the cost of a fresh builder for every variation.

Yes, and every build is independentOur pick

Each build() copies what it keeps (line 40 copies the airline set), so changing the builder later never reaches a search built earlier. One builder can turn out a search, change its date and turn out another. A build that fails leaves the builder as it was, so the caller can fix a value and try again.

Step 6: why the search must never change

The results page caches flights by search, so the same search never asks the flight catalog twice:

results/SearchService.javalines 18–27 of 32
    public List<Flight> search(FlightSearch search) {        Objects.requireNonNull(search, "search");        List<Flight> cached = cache.get(search);        if (cached != null) {            return cached;        }        List<Flight> flights = List.copyOf(catalog.flightsFor(search));        cache.put(search, flights);        return flights;    }

A FlightSearch is a safe key for three reasons. It cannot change after it goes into the map. equals compares every field. And hashCode uses the same fields, so two equal searches land in the same place in the map. The setter object from the first version failed on the first point. The demo's fifth search builds the family trip again, calling the methods in a different order, and the catalog is not asked again.

Line 24 also copies the catalog's answer with List.copyOf, so code that receives the cached list cannot change it for the next caller. This cache keeps every search forever and is meant for one thread. A real one would drop old entries and, if many request threads shared it, use a ConcurrentHashMap. It is here to show what a key needs.

The finished design

The finished design
FlightSearch.Builder is a static nested class. It holds the values while they are chosen and is the only caller of FlightSearch's private constructor. A finished FlightSearch keeps its values in final fields, with Airport (a record) and CabinClass (an enum) as its building blocks. A broken rule comes back as an InvalidSearchException with a list of problems. SearchService uses a FlightSearch as the key of its cache, and asks a FlightCatalog, an interface, for flights it has not seen.FlightSearch.Builder is a static nested class. It holds the values while they are chosen and is the only caller of FlightSearch's private constructor. A finished FlightSearch keeps its values in final fields, with Airport (a record) and CabinClass (an enum) as its building blocks. A broken rule comes back as an InvalidSearchException with a list of problems. SearchService uses a FlightSearch as the key of its cache, and asks a FlightCatalog, an interface, for flights it has not seen.
The builder creates the search. Nothing else can. FlightSearch.Builder is a static nested class. It holds the values while they are chosen and is the only caller of FlightSearch's private constructor. A finished FlightSearch keeps its values in final fields, with Airport (a record) and CabinClass (an enum) as its building blocks. A broken rule comes back as an InvalidSearchException with a list of problems. SearchService uses a FlightSearch as the key of its cache, and asks a FlightCatalog, an interface, for flights it has not seen.

Here is one build, traced through the objects:

One build, traced
The page creates a builder with the three required values (1) and sets the optional ones by name (2). It calls build() (3), which calls the private constructor. The constructor copies every value and the airline set (4), then runs problems() on its own copies (5). If the list is empty, the finished search goes back to the page (6). If not, the constructor throws one InvalidSearchException holding every problem.The page creates a builder with the three required values (1) and sets the optional ones by name (2). It calls build() (3), which calls the private constructor. The constructor copies every value and the airline set (4), then runs problems() on its own copies (5). If the list is empty, the finished search goes back to the page (6). If not, the constructor throws one InvalidSearchException holding every problem.
The builder only collects. The product copies, checks, and either exists or does not. The page creates a builder with the three required values (1) and sets the optional ones by name (2). It calls build() (3), which calls the private constructor. The constructor copies every value and the airline set (4), then runs problems() on its own copies (5). If the list is empty, the finished search goes back to the page (6). If not, the constructor throws one InvalidSearchException holding every problem.

The whole project is below. Click any class name in the code to open that class.

searchFlightSearch.java
package search; import java.time.LocalDate;import java.util.ArrayList;import java.util.Collections;import java.util.LinkedHashSet;import java.util.List;import java.util.Objects;import java.util.Optional;import java.util.OptionalInt;import java.util.Set;import java.util.TreeSet; public final class FlightSearch {    public static final int MAX_SEATS = 9;     private final Airport from;    private final Airport to;    private final LocalDate departure;    private final LocalDate returnDate;    private final int adults;    private final int children;    private final int infants;    private final CabinClass cabin;    private final boolean nonStopOnly;    private final Integer maxPrice;    private final Set<String> preferredAirlines;     private FlightSearch(Builder builder) {        this.from = builder.from;        this.to = builder.to;        this.departure = builder.departure;        this.returnDate = builder.returnDate;        this.adults = builder.adults;        this.children = builder.children;        this.infants = builder.infants;        this.cabin = builder.cabin;        this.nonStopOnly = builder.nonStopOnly;        this.maxPrice = builder.maxPrice;        this.preferredAirlines = Collections.unmodifiableSet(new TreeSet<>(builder.preferredAirlines));         // The rules read the final fields, so they check exactly what this search keeps.        List<String> problems = problems();        if (!problems.isEmpty()) {            throw new InvalidSearchException(problems);        }    }     private List<String> problems() {        List<String> problems = new ArrayList<>();        if (from.equals(to)) {            problems.add("From and to are the same airport");        }        if (returnDate != null && returnDate.isBefore(departure)) {            problems.add("The return date is before the departure date");        }        if (adults < 1) {            problems.add("At least one adult must travel");        }        if (children < 0 || infants < 0) {            problems.add("Passenger counts cannot be negative");        }        if (adults >= 1 && infants > adults) {            problems.add("More infants (" + infants + ") than adults (" + adults + "): each infant sits on an adult's lap");        }        if ((long) adults + children > MAX_SEATS) {            problems.add("At most " + MAX_SEATS + " seats per booking");        }        if (maxPrice != null && maxPrice <= 0) {            problems.add("The price limit must be more than $0");        }        return problems;    }     public Airport from() {        return from;    }     public Airport to() {        return to;    }     public LocalDate departure() {        return departure;    }     public Optional<LocalDate> returnDate() {        return Optional.ofNullable(returnDate);    }     public int adults() {        return adults;    }     public int children() {        return children;    }     public int infants() {        return infants;    }     public int seats() {        return adults + children;    }     public CabinClass cabin() {        return cabin;    }     public boolean nonStopOnly() {        return nonStopOnly;    }     public OptionalInt maxPrice() {        return maxPrice == null ? OptionalInt.empty() : OptionalInt.of(maxPrice);    }     public Set<String> preferredAirlines() {        return preferredAirlines;    }     public Builder toBuilder() {        Builder builder = new Builder(from, to, departure)                .adults(adults)                .children(children)                .infants(infants)                .cabin(cabin)                .nonStopOnly(nonStopOnly);        if (returnDate != null) {            builder.returningOn(returnDate);        }        if (maxPrice != null) {            builder.maxPrice(maxPrice);        }        for (String airline : preferredAirlines) {            builder.preferAirline(airline);        }        return builder;    }     @Override    public boolean equals(Object other) {        if (this == other) {            return true;        }        if (!(other instanceof FlightSearch that)) {            return false;        }        return from.equals(that.from)                && to.equals(that.to)                && departure.equals(that.departure)                && Objects.equals(returnDate, that.returnDate)                && adults == that.adults                && children == that.children                && infants == that.infants                && cabin == that.cabin                && nonStopOnly == that.nonStopOnly                && Objects.equals(maxPrice, that.maxPrice)                && preferredAirlines.equals(that.preferredAirlines);    }     @Override    public int hashCode() {        return Objects.hash(from, to, departure, returnDate, adults, children, infants,                cabin, nonStopOnly, maxPrice, preferredAirlines);    }     @Override    public String toString() {        StringBuilder text = new StringBuilder();        text.append(from).append(" to ").append(to).append(", ").append(departure);        text.append(returnDate == null ? ", one way" : ", back " + returnDate);        text.append(", ").append(adults).append(adults == 1 ? " adult" : " adults");        if (children > 0) {            text.append(", ").append(children).append(children == 1 ? " child" : " children");        }        if (infants > 0) {            text.append(", ").append(infants).append(infants == 1 ? " infant" : " infants");        }        text.append(", ").append(cabin);        if (nonStopOnly) {            text.append(", non-stop");        }        if (maxPrice != null) {            text.append(", up to $").append(maxPrice);        }        if (!preferredAirlines.isEmpty()) {            text.append(", airlines ").append(String.join("/", preferredAirlines));        }        return text.toString();    }     public static final class Builder {        private final Airport from;        private final Airport to;        private LocalDate departure;        private LocalDate returnDate;        private int adults = 1;        private int children = 0;        private int infants = 0;        private CabinClass cabin = CabinClass.ECONOMY;        private boolean nonStopOnly = false;        private Integer maxPrice;        private final Set<String> preferredAirlines = new LinkedHashSet<>();         public Builder(Airport from, Airport to, LocalDate departure) {            this.from = Objects.requireNonNull(from, "from");            this.to = Objects.requireNonNull(to, "to");            this.departure = Objects.requireNonNull(departure, "departure");        }         public Builder departingOn(LocalDate date) {            this.departure = Objects.requireNonNull(date, "date");            return this;        }         public Builder returningOn(LocalDate date) {            this.returnDate = Objects.requireNonNull(date, "date");            return this;        }         public Builder oneWay() {            this.returnDate = null;            return this;        }         public Builder adults(int count) {            this.adults = count;            return this;        }         public Builder children(int count) {            this.children = count;            return this;        }         public Builder infants(int count) {            this.infants = count;            return this;        }         public Builder cabin(CabinClass cabin) {            this.cabin = Objects.requireNonNull(cabin, "cabin");            return this;        }         public Builder nonStopOnly(boolean nonStopOnly) {            this.nonStopOnly = nonStopOnly;            return this;        }         public Builder maxPrice(int dollars) {            this.maxPrice = dollars;            return this;        }         public Builder preferAirline(String code) {            Objects.requireNonNull(code, "code");            if (!code.matches("[A-Z0-9]{2}")) {                throw new IllegalArgumentException("Not an airline code: " + code);            }            preferredAirlines.add(code);            return this;        }         public FlightSearch build() {            return new FlightSearch(this);        }    }}
Click a class name in the code to open its fileJava · 271 lines · 535 in the project

The demo in demo/Main.java builds five searches against a small fake catalog. In this catalog, a price limit applies to the whole booking: the fare times the number of seats.

$ java demo.Main
1. Only the required values
   BLR to DEL, 2026-12-20, one way, 1 adult, ECONOMY
   6E 6012  1 stop(s)  $420 a seat
   6E 2131  0 stop(s)  $540 a seat
   UK 812  0 stop(s)  $590 a seat
   AI 504  0 stop(s)  $610 a seat
2. A family trip with filters
   BLR to DEL, 2026-12-20, back 2026-12-27, 2 adults, 1 child, 1 infant, ECONOMY, non-stop, up to $2000, airlines 6E/AI
   6E 2131  0 stop(s)  $540 a seat
   AI 504  0 stop(s)  $610 a seat
3. A search with three mistakes
   problem: From and to are the same airport
   problem: The return date is before the departure date
   problem: More infants (2) than adults (1): each infant sits on an adult's lap
4. The date strip: the family trip, one day earlier and later
   2026-12-19: from $630 a seat
   2026-12-20: from $540 a seat
   2026-12-21: from $490 a seat
   the original still leaves on 2026-12-20
5. The family trip again, built from scratch
   equal to the first: true, catalog calls added: 0

The first search gives only the required values, so it gets every default: one way, one adult, economy, and all four flights. The family trip has three seats and a limit of $2,000. The one-stop flight is filtered out by non-stop only, and UK 812 by the airline filter, leaving two. The third search breaks three rules and gets all three messages. The date strip builds three searches from the family trip, and the original still leaves on the 20th. The fifth search sets the same values in a different order and equals the family trip, so the catalog is not called again.

What it costs

A builder makes one change cheap: adding an optional value touches no existing call. Every search the code already builds keeps working, and the new value takes its default.

The cost is the number of places each value lives. A new "baggage included" filter has to be added in eight places in FlightSearch.java. The compiler catches some omissions: a final field that the constructor never sets does not compile. Two of the eight, toBuilder and equals, compile and fail silently. Leaving the value out of hashCode alone only makes the cache slower, because equal searches still get equal hash codes.

Where one new value has to go
On the left are the eight places a new value goes in FlightSearch.java: the product's field, the constructor's copy, the accessor, the builder's field with its default, the builder's method, toBuilder, equals and hashCode. The two marked amber compile and fail silently if forgotten. Forgetting toBuilder drops the value from every date-strip search. Leaving the value out of both equals and hashCode makes two different searches share one cache entry. On the right, a record needs one change, and the compiler then finds every call that has to change with it.On the left are the eight places a new value goes in FlightSearch.java: the product's field, the constructor's copy, the accessor, the builder's field with its default, the builder's method, toBuilder, equals and hashCode. The two marked amber compile and fail silently if forgotten. Forgetting toBuilder drops the value from every date-strip search. Leaving the value out of both equals and hashCode makes two different searches share one cache entry. On the right, a record needs one change, and the compiler then finds every call that has to change with it.
Adding one optional value means eight edits, and two of the mistakes go unnoticed. On the left are the eight places a new value goes in FlightSearch.java: the product's field, the constructor's copy, the accessor, the builder's field with its default, the builder's method, toBuilder, equals and hashCode. The two marked amber compile and fail silently if forgotten. Forgetting toBuilder drops the value from every date-strip search. Leaving the value out of both equals and hashCode makes two different searches share one cache entry. On the right, a record needs one change, and the compiler then finds every call that has to change with it.

So the trade is this: a builder protects every caller, and the price is paid once, inside the product. That is a good trade when there are many callers and many values. It is a bad one for a small object built in two places.

When a builder is too much

With a few values, all required, a record is shorter and just as safe. Its compact constructor checks the values:

Sketchnot part of the final code
record Seat(String flight, int row, char letter) {    Seat {        if (row < 1) {            throw new IllegalArgumentException("Rows start at 1");        }    }}

With a few common shapes, a named static method that returns a ready-made object, which the Factory pattern page calls a second, smaller kind of factory, does the job of a builder.

Sketchnot part of the final code
record Passengers(int adults, int children, int infants) {    static Passengers adults(int count) {        return new Passengers(count, 0, 0);    }     static Passengers family(int adults, int children) {        return new Passengers(adults, children, 0);    }}

A builder starts to pay when there are several optional values, or several values of the same type next to each other. The Parking Lot design skips a builder for exactly this reason. Its five constructor arguments are all required and all of different types, so the compiler catches a mix-up.

Builder or Factory?

Both patterns create objects for the caller, and both hide a constructor. They answer different questions.

BuilderFactory
What the caller decidesEvery value, one at a timeWhich kind of object, often from a single input
What comes backOne class, filled in the caller's wayOne of several classes, behind an interface
When the object is madeWhen the caller calls build()In one call
ExampleA flight search with eleven valuesAn exporter chosen by format name: CSV, JSON, HTML or Markdown

A short way to say it: a factory chooses which class to create, and a builder lets the caller choose the values of one class. The Factory pattern page builds the exporter from that last row.

In an interview

The Builder pattern fits inside many low-level design questions. Examples are the search request in a flight or movie booking system, a notification with optional parts, a request in an HTTP client, and a configuration object. Test data for any of them fits too. In each one, the sign is an object with a few required values and many optional ones.

A good order for presenting it:

  1. List the values out loud, split into required and optional, with the default for each optional one.
  2. Write the builder's constructor with the required values, two or three optional methods, and build().
  3. Say where the rules are checked and how errors come back, then write the check for one rule that reads two values, such as infants and adults.

Common mistakes:

  • A product with setters, or a list field shared with the builder. The product then changes after it is built. Copy every collection the product keeps.
  • Rules checked only in the builder's methods. A rule that reads two values cannot run until both are set. Rules that span values belong in one place, run once every value is in.
  • A builder declared without static. A non-static nested class needs an existing FlightSearch to hang from, so the first search could never be built, and new FlightSearch.Builder(…) does not compile.
  • A builder for three required values. That is a constructor with extra steps.
  • A field missing from toBuilder, or from both equals and hashCode. The code compiles and the bug shows up far away, as a filter that vanishes when the date changes or two searches sharing a cache entry.

Summary

  • Use a builder when an object has a few required values, many optional ones, and rules that tie values together.
  • Put the required values in the builder's constructor and give every optional value a named method with a default.
  • Give the product a private constructor, final fields and no setters. Copy every collection it keeps.
  • Check every rule in one place once all the values are in, and report every broken rule together.
  • toBuilder() gives a changed copy without changing the original.
  • With few values, all required, a record or a named static method is simpler.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.