Practice: Builder for complex order objects
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
A ShopLite order needs a customer, items and an address, and may also have a coupon, a gift note or a delivery slot. A constructor with six arguments is hard to read and easy to get wrong. This checkpoint reviews the Builder fix.
An order with items, address, coupon, gift note and delivery slot
The Builder pattern creates a complex object step by step through a separate builder object, then returns the finished object from build().
Every builder setter returns the builder itself, so calls chain: Order.builder("C42").item(...).shipTo(...).coupon("DIWALI10").build().
Example 1 · Building orders with only the parts you need
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Optional;
record OrderLine(String sku, int qty, BigDecimal price) { }
record Address(String line1, String city, String pin) { }
enum DeliverySlot { STANDARD, MORNING_7_TO_10, EVENING_6_TO_9 }
final class Order { private final String customerId; private final List<OrderLine> items; private final Address shipTo; private final String coupon; // may be null private final String giftNote; // may be null private final DeliverySlot slot;
private Order(Builder b) { this.customerId = b.customerId; this.items = List.copyOf(b.items); this.shipTo = b.shipTo; this.coupon = b.coupon; this.giftNote = b.giftNote; this.slot = b.slot; }
static Builder builder(String customerId) { return new Builder(customerId); }
List<OrderLine> items() { return items; } Optional<String> coupon() { return Optional.ofNullable(coupon); } Optional<String> giftNote() { return Optional.ofNullable(giftNote); }
public String toString() { return "Order[" + customerId + ", items=" + items.size() + ", to " + shipTo.city() + ", coupon=" + coupon().orElse("-") + ", gift=" + giftNote().map(n -> "\"" + n + "\"").orElse("-") + ", slot=" + slot + "]"; }
static final class Builder { private final String customerId; private final List<OrderLine> items = new ArrayList<>(); private Address shipTo; private String coupon; private String giftNote; private DeliverySlot slot = DeliverySlot.STANDARD;
private Builder(String customerId) { this.customerId = customerId; }
Builder item(String sku, int qty, String price) { items.add(new OrderLine(sku, qty, new BigDecimal(price))); return this; } Builder shipTo(Address a) { this.shipTo = a; return this; } Builder coupon(String code) { this.coupon = code; return this; } Builder giftNote(String note) { this.giftNote = note; return this; } Builder slot(DeliverySlot s) { this.slot = s; return this; }
Order build() { if (customerId == null || customerId.isBlank()) throw new IllegalStateException("customer is required"); if (items.isEmpty()) throw new IllegalStateException("an order needs at least one item"); if (shipTo == null) throw new IllegalStateException("shipping address is required"); if (giftNote != null && giftNote.length() > 100) throw new IllegalStateException("gift note is longer than 100 characters"); return new Order(this); } }}
public class OrderBuilderDemo { public static void main(String[] args) { Address home = new Address("12 MG Road", "Bengaluru", "560001");
Order simple = Order.builder("C42") .item("MUG", 2, "249.00") .shipTo(home) .build();
Order gift = Order.builder("C77") .item("TSHIRT", 1, "399.00") .item("CARD", 1, "49.00") .shipTo(new Address("4 Park Street", "Kolkata", "700016")) .coupon("DIWALI10") .giftNote("Happy Diwali, Didi") .slot(DeliverySlot.EVENING_6_TO_9) .build();
System.out.println(simple); System.out.println(gift); System.out.println("Gift note present? " + gift.giftNote().isPresent() + " / " + simple.giftNote().isPresent()); }}Order[C42, items=1, to Bengaluru, coupon=-, gift=-, slot=STANDARD] Order[C77, items=2, to Kolkata, coupon=DIWALI10, gift="Happy Diwali, Didi", slot=EVENING_6_TO_9] Gift note present? true / false
What this code does
- The simple order sets three parts; the gift order sets six. Neither call has a
nullin it, and each value is named by its method. - Optional parts are exposed as
Optional<String>, so callers must handle "no coupon" instead of meeting anull. - The slot defaults to
STANDARDin the builder, which is why the simple order shows it without setting it.
The alternative, a constructor with six parameters, is hard to read (which null is the coupon?) and leads to many overloaded constructors, one per combination of optional parts. With a builder, every value is named at the call site, and the parts you do not need are simply not called.
Required vs optional fields and validation in build()
A required field must be present for the object to make sense; an optional field has a sensible default or may be empty.
Put required values the builder cannot work without in builder(...) itself (here the customer id), give optional ones defaults (slot STANDARD), and check every rule in build().
Example 2 · build() rejects incomplete orders
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Optional;import java.util.function.Supplier;
record OrderLine(String sku, int qty, BigDecimal price) { }
record Address(String line1, String city, String pin) { }
enum DeliverySlot { STANDARD, MORNING_7_TO_10, EVENING_6_TO_9 }
final class Order { private final String customerId; private final List<OrderLine> items; private final Address shipTo; private final String coupon; // may be null private final String giftNote; // may be null private final DeliverySlot slot;
private Order(Builder b) { this.customerId = b.customerId; this.items = List.copyOf(b.items); this.shipTo = b.shipTo; this.coupon = b.coupon; this.giftNote = b.giftNote; this.slot = b.slot; }
static Builder builder(String customerId) { return new Builder(customerId); }
List<OrderLine> items() { return items; } Optional<String> coupon() { return Optional.ofNullable(coupon); } Optional<String> giftNote() { return Optional.ofNullable(giftNote); }
public String toString() { return "Order[" + customerId + ", items=" + items.size() + ", to " + shipTo.city() + ", coupon=" + coupon().orElse("-") + ", gift=" + giftNote().map(n -> "\"" + n + "\"").orElse("-") + ", slot=" + slot + "]"; }
static final class Builder { private final String customerId; private final List<OrderLine> items = new ArrayList<>(); private Address shipTo; private String coupon; private String giftNote; private DeliverySlot slot = DeliverySlot.STANDARD;
private Builder(String customerId) { this.customerId = customerId; }
Builder item(String sku, int qty, String price) { items.add(new OrderLine(sku, qty, new BigDecimal(price))); return this; } Builder shipTo(Address a) { this.shipTo = a; return this; } Builder coupon(String code) { this.coupon = code; return this; } Builder giftNote(String note) { this.giftNote = note; return this; } Builder slot(DeliverySlot s) { this.slot = s; return this; }
Order build() { if (customerId == null || customerId.isBlank()) throw new IllegalStateException("customer is required"); if (items.isEmpty()) throw new IllegalStateException("an order needs at least one item"); if (shipTo == null) throw new IllegalStateException("shipping address is required"); if (giftNote != null && giftNote.length() > 100) throw new IllegalStateException("gift note is longer than 100 characters"); return new Order(this); } }}
public class OrderValidationDemo { static void tryBuild(String label, Supplier<Order> attempt) { try { System.out.println(label + ": " + attempt.get()); } catch (IllegalStateException e) { System.out.println(label + ": rejected, " + e.getMessage()); } }
public static void main(String[] args) { Address addr = new Address("7 Anna Salai", "Chennai", "600002"); tryBuild("No items", () -> Order.builder("C1").shipTo(addr).build()); tryBuild("No address", () -> Order.builder("C1").item("PEN", 3, "20.00").build()); tryBuild("Long note", () -> Order.builder("C1").item("PEN", 3, "20.00").shipTo(addr) .giftNote("Many happy returns! ".repeat(6)).build()); tryBuild("Blank customer", () -> Order.builder(" ").item("PEN", 3, "20.00").shipTo(addr).build()); tryBuild("Valid", () -> Order.builder("C1").item("PEN", 3, "20.00").shipTo(addr).build()); }}No items: rejected, an order needs at least one item No address: rejected, shipping address is required Long note: rejected, gift note is longer than 100 characters Blank customer: rejected, customer is required Valid: Order[C1, items=1, to Chennai, coupon=-, gift=-, slot=STANDARD]
What this code does
- Every rule about the whole order lives in
build(), so there is one place to read and test them. - A rejected build throws before the private
Orderconstructor runs, so no half-valid order object ever exists. - The messages say what is missing, which is what a support engineer needs when a checkout request fails.
build() is the one place where the whole order is checked together: at least one item, an address, a gift note of at most 100 characters. It throws IllegalStateException with a clear message, so an invalid Order object can never exist.
Immutable Order with defensive copies of item lists
An immutable object cannot change after it is built: all fields are private final, there are no setters, and the class is final.
A defensive copy is a copy taken at the boundary so that outside code cannot change the object's internals through a shared reference.
Example 3 · Bug: the built order shares the builder's list
import java.util.ArrayList;import java.util.List;
final class LeakyOrder { private final List<String> items;
private LeakyOrder(Builder b) { this.items = b.items; // shares the builder's list }
List<String> items() { return items; }
static final class Builder { private final List<String> items = new ArrayList<>(); Builder item(String sku) { items.add(sku); return this; } LeakyOrder build() { return new LeakyOrder(this); } }}
public class LeakyBuilderDemo { public static void main(String[] args) { LeakyOrder.Builder builder = new LeakyOrder.Builder().item("MUG"); LeakyOrder placed = builder.build(); System.out.println("Placed order: " + placed.items());
builder.item("TSHIRT"); // reuse the builder for the next cart System.out.println("Placed order now: " + placed.items());
placed.items().add("FREE-LAPTOP"); // callers can change it too System.out.println("After a caller edits it: " + placed.items()); }}Placed order: [MUG] Placed order now: [MUG, TSHIRT] After a caller edits it: [MUG, TSHIRT, FREE-LAPTOP]
What this code does
finalonly stops the field from pointing at another list; the list it points at can still change.- Reusing the builder adds a T-shirt to an order that was already placed, and any caller can add items through
items(). - Both leaks come from sharing one mutable
ArrayListbetween the builder, the order and its callers.
Example 4 · Fix: a defensive copy in the constructor
import java.util.ArrayList;import java.util.List;
final class SafeOrder { private final List<String> items;
private SafeOrder(Builder b) { this.items = List.copyOf(b.items); // own, unmodifiable copy }
List<String> items() { return items; }
static final class Builder { private final List<String> items = new ArrayList<>(); Builder item(String sku) { items.add(sku); return this; } SafeOrder build() { return new SafeOrder(this); } }}
public class SafeBuilderDemo { public static void main(String[] args) { SafeOrder.Builder builder = new SafeOrder.Builder().item("MUG"); SafeOrder placed = builder.build(); builder.item("TSHIRT"); System.out.println("Placed order: " + placed.items());
try { placed.items().add("FREE-LAPTOP"); } catch (UnsupportedOperationException e) { System.out.println("Caller cannot add items: " + e.getClass().getSimpleName()); } System.out.println("Next order from the same builder: " + builder.build().items()); }}Placed order: [MUG] Caller cannot add items: UnsupportedOperationException Next order from the same builder: [MUG, TSHIRT]
What this code does
List.copyOftakes a snapshot when the order is built, so later changes to the builder do not reach it.- The copy is unmodifiable, so
items()can return it directly: callers getUnsupportedOperationExceptionif they try to add. - The builder can be reused safely; each
build()produces an independent order.
The trap is the item list. If Order keeps the builder's own ArrayList, then adding an item to the builder after build() silently changes an order that was already placed. List.copyOf(b.items) in the constructor gives the order its own unmodifiable list and closes the leak.
Find the bug
Find the leak
Each snippet lets outside code change a placed order. Tap the line to fix.
The order constructor.
Round 1 of 2Nested builders for address and line items
A nested builder builds a part of a bigger object with its own builder: Address has Address.Builder, and an order line has its own small builder.
The order builder accepts a Consumer<Address.Builder>, so the call reads as one block: .shipTo(a -> a.line1("12 MG Road").city("Bengaluru").pin("560001")).
Example 5 · Nested builders for address and line items
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;
record Address(String line1, String city, String pin) { static final class Builder { private String line1, city, pin; Builder line1(String v) { line1 = v; return this; } Builder city(String v) { city = v; return this; } Builder pin(String v) { pin = v; return this; } Address build() { if (line1 == null || city == null) throw new IllegalStateException("address line and city are required"); if (pin == null || !pin.matches("\\d{6}")) throw new IllegalStateException("PIN code must be 6 digits"); return new Address(line1, city, pin); } }}
record OrderLine(String sku, int qty, BigDecimal price) { static final class Builder { private String sku; private int qty = 1; private BigDecimal price; Builder sku(String v) { sku = v; return this; } Builder qty(int v) { qty = v; return this; } Builder price(String v) { price = new BigDecimal(v); return this; } OrderLine build() { if (sku == null || price == null) throw new IllegalStateException("sku and price are required"); if (qty < 1) throw new IllegalStateException("quantity must be at least 1 for " + sku); return new OrderLine(sku, qty, price); } }}
record Order(String customerId, List<OrderLine> items, Address shipTo) { Order { items = List.copyOf(items); }
static final class Builder { private final String customerId; private final List<OrderLine> items = new ArrayList<>(); private Address shipTo; Builder(String customerId) { this.customerId = customerId; }
Builder item(Consumer<OrderLine.Builder> spec) { OrderLine.Builder b = new OrderLine.Builder(); spec.accept(b); items.add(b.build()); return this; }
Builder shipTo(Consumer<Address.Builder> spec) { Address.Builder b = new Address.Builder(); spec.accept(b); shipTo = b.build(); return this; }
Order build() { if (items.isEmpty() || shipTo == null) throw new IllegalStateException("items and address are required"); return new Order(customerId, items, shipTo); } }}
public class NestedBuilderDemo { public static void main(String[] args) { Order order = new Order.Builder("C42") .item(i -> i.sku("MUG").qty(2).price("249.00")) .item(i -> i.sku("CARD").price("49.00")) .shipTo(a -> a.line1("12 MG Road").city("Bengaluru").pin("560001")) .build(); System.out.println(order.items()); System.out.println(order.shipTo());
try { new Order.Builder("C43").item(i -> i.sku("PEN").price("20.00")) .shipTo(a -> a.line1("3 Ring Road").city("Delhi").pin("1100")) .build(); } catch (IllegalStateException e) { System.out.println("Rejected: " + e.getMessage()); } }}[OrderLine[sku=MUG, qty=2, price=249.00], OrderLine[sku=CARD, qty=1, price=49.00]] Address[line1=12 MG Road, city=Bengaluru, pin=560001] Rejected: PIN code must be 6 digits
What this code does
- Each part has its own builder and its own rules: the address checks the 6-digit PIN, the line checks the quantity and defaults it to 1.
- The order builder takes a
Consumerof the nested builder, so the call reads top to bottom like the order itself. - The record's compact constructor (
Order { items = List.copyOf(items); }) makes the defensive copy even for code that skips the builder.
Each part of the order validates itself in its own build() (a PIN code must be 6 digits; a quantity at least 1), and the order builder only checks the rules about the whole order.
Finish up
Mark complete & continue
Next: Review and improve an existing design