Part 3 of 6 · 2 min read
The builder
Set options by name, then build once.
EJ's answer joins the safety of a constructor to the readable look of setters. The caller makes a small helper object, the builder, sets options on it by name, and calls build to get the real object. EJ calls this a form of the Builder pattern from GoF.
final class BookingRequest {
private final String room;
private final int start, end, attendees;
private final boolean projector, catering;
private BookingRequest(Builder b) {
room = b.room; start = b.start; end = b.end;
attendees = b.attendees; projector = b.projector; catering = b.catering;
}
static Builder builder(String room, int start, int end) { return new Builder(room, start, end); }
static final class Builder {
private final String room;
private final int start, end;
private int attendees = 1;
private boolean projector, catering;
private Builder(String room, int start, int end) {
this.room = room; this.start = start; this.end = end;
}
Builder attendees(int n) { attendees = n; return this; }
Builder projector(boolean v) { projector = v; return this; }
Builder catering(boolean v) { catering = v; return this; }
BookingRequest build() {
if (end <= start) throw new IllegalStateException("end must be after start");
if (catering && attendees < 5) throw new IllegalStateException("catering needs 5 or more people");
return new BookingRequest(this);
}
}
}
A caller writes BookingRequest.builder("A1", 9, 11).attendees(8).projector(true).build(). The result prints as "A1 9-11 people=8 projector=true catering=false". Each option has a name, and the required ones are asked for up front. Leaving out optional items gives their defaults, so builder("B2", 14, 15).build() gives one attendee and no extras.
The checks sit in build. Asking for catering with 2 attendees throws "catering needs 5 or more people", and no half-built request ever exists. EJ advises validating each value early, inside the builder's methods, and testing rules that span several fields at the moment the object is made. Because the fields are final and have no setters, the result is immutable.
Builder
A builder is a helper object that collects the settings for another object, one named call at a time, and then creates that object in a single step.
Example: BookingRequest.builder(...).attendees(8).build().
Check yourself:
1. What does builder("B2", 14, 15).build() print for attendees?
2. Where are the cross-field rules checked?
3. Why is the finished object immutable?