Skip to lesson

Builder for objects with many fields

ShopLite's Receipt has seven fields. A call like new Receipt("ORD-3", "Meena", 1200, 100, 40) still compiles when the delivery fee and the discount are swapped, and the customer is overcharged.

Telescoping constructors and why they hurt

Telescoping constructors are a chain of constructors, each taking one more parameter than the last and passing defaults to the next.

ShopLite's Receipt has seven fields, so it needs four constructors. Look at the calls, and at what happens when two double values are swapped.

Example 1 · Telescoping constructors and a silent swap

TelescopingDemo.javaJava
class Receipt {    private final String orderId;    private final String customer;    private final double subtotal;    private final double deliveryFee;    private final double discount;    private final String couponCode;    private final boolean giftWrap;
    Receipt(String orderId, String customer, double subtotal) {        this(orderId, customer, subtotal, 0);    }
    Receipt(String orderId, String customer, double subtotal, double deliveryFee) {        this(orderId, customer, subtotal, deliveryFee, 0);    }
    Receipt(String orderId, String customer, double subtotal, double deliveryFee, double discount) {        this(orderId, customer, subtotal, deliveryFee, discount, null, false);    }
    Receipt(String orderId, String customer, double subtotal, double deliveryFee,            double discount, String couponCode, boolean giftWrap) {        this.orderId = orderId;        this.customer = customer;        this.subtotal = subtotal;        this.deliveryFee = deliveryFee;        this.discount = discount;        this.couponCode = couponCode;        this.giftWrap = giftWrap;    }
    double total() {        return subtotal + deliveryFee - discount + (giftWrap ? 49 : 0);    }
    String summary() {        return String.format("%s for %s: Rs %.2f%s", orderId, customer, total(),                couponCode == null ? "" : " (coupon " + couponCode + ")");    }}
public class TelescopingDemo {    public static void main(String[] args) {        Receipt a = new Receipt("ORD-1", "Asha", 360, 40);        Receipt b = new Receipt("ORD-2", "Ravi", 1799, 0, 100, "FEST100", true);        // Meant: delivery fee 40, discount 100. Swapped by mistake, and it still compiles:        Receipt c = new Receipt("ORD-3", "Meena", 1200, 100, 40);
        System.out.println(a.summary());        System.out.println(b.summary());        System.out.println(c.summary() + "   <- should be Rs 1140.00");    }}
Output
ORD-1 for Asha: Rs 400.00
ORD-2 for Ravi: Rs 1748.00 (coupon FEST100)
ORD-3 for Meena: Rs 1260.00   <- should be Rs 1140.00

What this code does

  • Four constructors exist only to supply defaults, and each new optional field would add another.
  • For ORD-3 the delivery fee and discount were swapped. Both are double, so the compiler accepted it and the customer was overcharged Rs 120.

Common mistake: swapping two arguments of the same type. The compiler accepts any double in any position, so only careful reading catches it, which does not scale. Every new optional field also adds yet another constructor.

Predict the output

Which total prints?

Read the call and pick the output.

Meant: delivery fee 40 and discount 80. The constructor order is subtotal, delivery fee, discount.

Receipt a = new Receipt("ORD-1", "Asha", 800, 80, 40);
System.out.println(a.total());

A static nested Builder with fluent setters and build()

A builder is a helper object that collects values one named step at a time and creates the final object in build(). In Java it is usually a static nested class.

Receipt.Builder has one method per field and a final build(). Each setter returns this, so the calls chain, and every value has a name.

Example 2 · A fluent Receipt.Builder

ReceiptBuilderDemo.javaJava
class Receipt {    private final String orderId;    private final String customer;    private final double subtotal;    private final double deliveryFee;    private final double discount;    private final String couponCode;    private final boolean giftWrap;
    private Receipt(Builder b) {                 // only the builder can create a Receipt        orderId = b.orderId;        customer = b.customer;        subtotal = b.subtotal;        deliveryFee = b.deliveryFee;        discount = b.discount;        couponCode = b.couponCode;        giftWrap = b.giftWrap;    }
    double total() {        return subtotal + deliveryFee - discount + (giftWrap ? 49 : 0);    }
    String summary() {        return String.format("%s for %s: Rs %.2f%s", orderId, customer, total(),                couponCode == null ? "" : " (coupon " + couponCode + ")");    }
    static class Builder {        private String orderId;        private String customer;        private double subtotal;        private double deliveryFee;        private double discount;        private String couponCode;        private boolean giftWrap;
        Builder orderId(String orderId) { this.orderId = orderId; return this; }        Builder customer(String customer) { this.customer = customer; return this; }        Builder subtotal(double subtotal) { this.subtotal = subtotal; return this; }        Builder deliveryFee(double fee) { this.deliveryFee = fee; return this; }        Builder discount(double discount) { this.discount = discount; return this; }        Builder coupon(String code) { this.couponCode = code; return this; }        Builder giftWrap(boolean giftWrap) { this.giftWrap = giftWrap; return this; }
        Receipt build() {            return new Receipt(this);        }    }}
public class ReceiptBuilderDemo {    public static void main(String[] args) {        Receipt meena = new Receipt.Builder()                .orderId("ORD-3")                .customer("Meena")                .subtotal(1200)                .deliveryFee(40)                .discount(100)                .build();
        Receipt ravi = new Receipt.Builder()                .orderId("ORD-2").customer("Ravi").subtotal(1799)                .discount(100).coupon("FEST100").giftWrap(true)                .build();
        Receipt asha = new Receipt.Builder().orderId("ORD-1").customer("Asha").subtotal(360).deliveryFee(40).build();
        System.out.println(meena.summary());        System.out.println(ravi.summary());        System.out.println(asha.summary());    }}
Output
ORD-3 for Meena: Rs 1140.00
ORD-2 for Ravi: Rs 1748.00 (coupon FEST100)
ORD-1 for Asha: Rs 400.00

What this code does

  • Meena's receipt now says deliveryFee(40) and discount(100) in words, so the swap from Example 1 is easy to see and the total is right.
  • Optional fields have defaults in the builder; Asha's receipt sets only the four values it needs.

A chain like .orderId("ORD-3").deliveryFee(40).discount(100).build() is called a fluent interface. Optional fields are simply left out, and the Receipt constructor is private so the builder is the only way in.

Common mistake: a setter that forgets return this. The chain then fails to compile at the next dot.

Fix the error

Fix the broken chain

Pick the line that makes the chain compile.

A setter must return the builder.

static class Builder {
void discount(double d) { this.discount = d; }
Receipt build() { return new Receipt(this); }
}
// the caller writes:
new Receipt.Builder().discount(100).build();

Error

error: void cannot be dereferenced
new Receipt.Builder().discount(100).build();
                              ^

Validating required fields in build()

Setters can be called in any order, so build() is the place to check the whole object. Here it rejects a missing customer and a discount bigger than the subtotal.

Example 3 · build() rejects incomplete or impossible receipts

ValidatingBuilderDemo.javaJava
class Receipt {    private final String orderId;    private final String customer;    private final double subtotal;    private final double deliveryFee;    private final double discount;    private final String couponCode;    private final boolean giftWrap;
    private Receipt(Builder b) {                 // only the builder can create a Receipt        orderId = b.orderId;        customer = b.customer;        subtotal = b.subtotal;        deliveryFee = b.deliveryFee;        discount = b.discount;        couponCode = b.couponCode;        giftWrap = b.giftWrap;    }
    double total() {        return subtotal + deliveryFee - discount + (giftWrap ? 49 : 0);    }
    String summary() {        return String.format("%s for %s: Rs %.2f%s", orderId, customer, total(),                couponCode == null ? "" : " (coupon " + couponCode + ")");    }
    static class Builder {        private String orderId;        private String customer;        private double subtotal;        private double deliveryFee;        private double discount;        private String couponCode;        private boolean giftWrap;
        Builder orderId(String orderId) { this.orderId = orderId; return this; }        Builder customer(String customer) { this.customer = customer; return this; }        Builder subtotal(double subtotal) { this.subtotal = subtotal; return this; }        Builder deliveryFee(double fee) { this.deliveryFee = fee; return this; }        Builder discount(double discount) { this.discount = discount; return this; }        Builder coupon(String code) { this.couponCode = code; return this; }        Builder giftWrap(boolean giftWrap) { this.giftWrap = giftWrap; return this; }
        Receipt build() {            if (orderId == null || orderId.isBlank()) throw new IllegalStateException("orderId is required");            if (customer == null || customer.isBlank()) throw new IllegalStateException("customer is required");            if (subtotal <= 0) throw new IllegalStateException("subtotal must be more than 0");            if (discount > subtotal) {                throw new IllegalStateException(String.format(                        "discount Rs %.2f is more than subtotal Rs %.2f", discount, subtotal));            }            return new Receipt(this);        }    }}
public class ValidatingBuilderDemo {    static void tryBuild(String label, Receipt.Builder builder) {        try {            System.out.println(label + ": " + builder.build().summary());        } catch (IllegalStateException e) {            System.out.println(label + ": rejected, " + e.getMessage());        }    }
    public static void main(String[] args) {        tryBuild("valid", new Receipt.Builder().orderId("ORD-7").customer("Kiran").subtotal(500).deliveryFee(40));        tryBuild("no customer", new Receipt.Builder().orderId("ORD-8").subtotal(500));        tryBuild("big discount", new Receipt.Builder().orderId("ORD-9").customer("Neel").subtotal(1200).discount(1500));    }}
Output
valid: ORD-7 for Kiran: Rs 540.00
no customer: rejected, customer is required
big discount: rejected, discount Rs 1500.00 is more than subtotal Rs 1200.00

What this code does

  • All checks run in one place, after every setter has been called, so rules that involve two fields (discount and subtotal) are easy to write.
  • IllegalStateException fits because the builder is in a state where it cannot build yet.

build() checks required fields (orderId, customer), single values (subtotal above 0) and rules across fields (discount not above subtotal), then throws IllegalStateException with a clear message. An object that passed build() is valid for its whole life.

Another style puts the required fields in the builder's own constructor, Receipt.builder("ORD-9"), so the compiler forces them and build() checks the rest.

Find the bug

Spot the validation bug

Each snippet has one wrong line. Tap it, then check the fix.

The caller may set the subtotal after the discount.

Round 1 of 2

Building immutable objects with final fields

An immutable object is an object whose state cannot change after it is created. It has final fields and no setters.

build() below copies the builder's values into final fields and takes a List.copyOf snapshot of the lines, so the finished receipt never changes.

Example 4 · An immutable receipt built from a reusable builder

ImmutableReceiptDemo.javaJava
import java.util.ArrayList;import java.util.List;
final class Receipt {    private final String orderId;    private final List<String> lines;    private final double subtotal;
    private Receipt(Builder b) {        orderId = b.orderId;        lines = List.copyOf(b.lines);            // a snapshot: later builder changes do not leak in        subtotal = b.subtotal;    }
    String orderId() { return orderId; }    List<String> lines() { return lines; }       // already unmodifiable    double subtotal() { return subtotal; }
    static Builder builder(String orderId) {        return new Builder(orderId);    }
    static final class Builder {        private final String orderId;        private final List<String> lines = new ArrayList<>();        private double subtotal;
        private Builder(String orderId) {            this.orderId = orderId;        }
        Builder line(String name, double price, int qty) {            lines.add(qty + " x " + name);            subtotal += price * qty;            return this;        }
        Receipt build() {            if (lines.isEmpty()) throw new IllegalStateException("a receipt needs at least one line");            return new Receipt(this);        }    }}
public class ImmutableReceiptDemo {    public static void main(String[] args) {        Receipt.Builder builder = Receipt.builder("ORD-9").line("Earbuds", 1499, 1).line("Pen set", 150, 2);        Receipt receipt = builder.build();
        builder.line("Hoodie", 899, 1);              // keep using the same builder        Receipt bigger = builder.build();
        System.out.printf("%s %s Rs %.2f%n", receipt.orderId(), receipt.lines(), receipt.subtotal());        System.out.printf("%s %s Rs %.2f%n", bigger.orderId(), bigger.lines(), bigger.subtotal());        try {            receipt.lines().add("1 x Free gift");        } catch (UnsupportedOperationException e) {            System.out.println("Receipt lines cannot be changed");        }    }}
Output
ORD-9 [1 x Earbuds, 2 x Pen set] Rs 1799.00
ORD-9 [1 x Earbuds, 2 x Pen set, 1 x Hoodie] Rs 2698.00
Receipt lines cannot be changed

What this code does

  • Adding the hoodie to the builder after the first build() did not change receipt, because the constructor took a List.copyOf snapshot.
  • Receipt.builder("ORD-9") makes the order id required through the builder's constructor; build() still checks that at least one line exists.

The builder is the mutable draft; the finished object has no setters. If build() handed over the builder's own ArrayList, later builder calls would change the finished receipt. List.copyOf copies the list and makes it unmodifiable, so even code that reads the receipt cannot add lines.

Predict the output

Shared list or snapshot?

Read the code and pick the exact output.

Which list sees the later change?

List<String> draft = new ArrayList<>(List.of("Pen"));
List<String> shared = draft;
List<String> snapshot = List.copyOf(draft);
draft.add("Bag");
System.out.println(shared + " " + snapshot);

Builder vs records and constructor parameters

A compact constructor is a record constructor written without a parameter list. It checks or adjusts the values before they are stored.

A builder costs a second class and one method per field. Below, a record guards a small value, and a record with a nested builder handles many options.

Example 5 · A record for a small value, a builder for many options

RecordOrBuilderDemo.javaJava
// Two required fields: a record with a compact constructor is enoughrecord Address(String city, String pin) {    Address {        if (pin == null || !pin.matches("\\d{6}")) {            throw new IllegalArgumentException("PIN must be 6 digits: " + pin);        }    }}
// Six fields, most optional: a record plus a nested builderrecord ProductSearch(String text, String category, int minPrice, int maxPrice,                     boolean inStockOnly, String sort) {
    static class Builder {        private String text = "";        private String category = "All";        private int minPrice = 0;        private int maxPrice = Integer.MAX_VALUE;        private boolean inStockOnly = false;        private String sort = "RELEVANCE";
        Builder text(String text) { this.text = text; return this; }        Builder category(String category) { this.category = category; return this; }        Builder maxPrice(int maxPrice) { this.maxPrice = maxPrice; return this; }        Builder inStockOnly() { this.inStockOnly = true; return this; }        Builder sortBy(String sort) { this.sort = sort; return this; }
        ProductSearch build() {            return new ProductSearch(text, category, minPrice, maxPrice, inStockOnly, sort);        }    }}
public class RecordOrBuilderDemo {    public static void main(String[] args) {        Address home = new Address("Pune", "411001");        System.out.println(home);        try {            new Address("Pune", "4110");        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }
        ProductSearch search = new ProductSearch.Builder()                .category("Electronics")                .maxPrice(2000)                .inStockOnly()                .build();        System.out.println(search);    }}
Output
Address[city=Pune, pin=411001]
PIN must be 6 digits: 4110
ProductSearch[text=, category=Electronics, minPrice=0, maxPrice=2000, inStockOnly=true, sort=RELEVANCE]

What this code does

  • Address has two required fields, so a record with a compact constructor gives validation, equals and toString with no builder.
  • ProductSearch has six fields with sensible defaults; the nested builder lets a caller set only category, maxPrice and inStockOnly by name.

When to use which:

  • 1 to 3 fields, all required: a constructor or a record is clearer.
  • Validation for a small value type: a record's compact constructor is enough.
  • 4 or more fields with several optional ones or defaults: a builder.
  • Same-type parameters that are easy to swap, such as several double amounts: a builder, even with fewer fields.

The two also combine: a record can have a nested builder, so the result keeps the record's equals, hashCode and toString while callers get named steps.

Next step

Check your understanding

10 quick questions