Builder
- Intent
- Separate the construction of a complex object from its representation, so it can be put together step by step and the same process can produce different results.
- Application
- A box class has a name, a time, a length, spots, a coach and a few options. Build it step by step with clear names and get, at the end, an immutable object that is always valid.
The coach sends the class to SessionController, which calls new TelescopingSession with seven arguments, highlighted in red.
SessionController calls MutableSession and feeds it setName, setCoach and the rest, highlighted in red.
ClassSession.Builder appears, highlighted, and hands over a ClassSession with build().
The builder, with coach Ana and beginnerFriendly already set, hands over the ClassSession with build(); both are highlighted.
The builder tries to hand over a ClassSession with capacity 0, and ClassSession, highlighted, rejects it.
SessionTemplates, highlighted, sends "beginner" to the builder, which hands over the ClassSession with build().
Hyrox prep · 18:00 travels from the coach to the controller, schedule() to ScheduleService and on to the builder, both highlighted, which hands over the ClassSession with build().
Inside the Spring context, RestClient.Builder, highlighted, takes baseUrl and defaultHeader and hands over a RestClient with build().
Final view: the coach, the controller, ScheduleService, SessionTemplates, the builder and the ClassSession, all inside the Spring context.
Step 1 of 9
Seven arguments in a row
The coach schedules a new class: Hyrox prep at 18:00, 60 minutes, 12 spots, with Ana, beginner-friendly and no waitlist.
The first version uses a telescoping constructor: one with two parameters, which calls one with three, which calls one with four… up to the one that has them all. And the call ends up like this: new TelescopingSession("Hyrox prep", LocalTime.of(18, 0), 60, 12, "Ana", true, false).
Step 2 of 9
The setters alternative
The other usual option is an empty object you fill in: new MutableSession() and then setName(...), setStartsAt(...), setCoach(...)…
It reads better, but the object exists before it's finished. Between one line and the next it has no start time, and if you forget a line, nobody notices. And setCapacity(0) is accepted without a word, and anyone can change it later.
Step 3 of 9
An object that builds the object
Builder puts someone in between: ClassSession.Builder.
- You create it with the essentials:
ClassSession.builder("Hyrox prep", LocalTime.of(18, 0)). - The rest are named methods (
minutes(),capacity(),coach()…) that store the value and return the builder itself so you can keep chaining. - The defaults (60 minutes, 12 spots) live in the builder.
build()hands over the finishedClassSession, an immutable record.
Step 4 of 9
The call reads on its own
Compare it with the start: ClassSession.builder("Hyrox prep", LocalTime.of(18, 0)), then .coach("Ana"), .beginnerFriendly() and, to finish, .build().
Every option says what it is, you don't write the defaults, and the order of the calls doesn't matter. beginnerFriendly() doesn't take a true you could mix up with another one: calling it is the decision.
Step 5 of 9
Valid or it doesn't exist
What if someone asks for capacity(0) or a beginner class with no coach? build() calls the record's constructor, and that constructor checks every rule in one place, at build() time: 15 to 120 minutes in steps of 15, between 1 and 30 spots, a coach required for beginners.
If something fails, it throws an exception with the reason and nothing gets created. Since the rules live in the constructor and not in the builder, they also apply to anyone who calls new ClassSession(...) directly.
Step 6 of 9
House recipes
The box always repeats the same classes. SessionTemplates is the pattern's director: it knows the recipes and calls the builder's steps in order.
"beginner": 75 minutes, 8 spots, a coach, beginner-friendly and with a waitlist."open-gym": 120 minutes, 20 spots and no coach.
In classic GoF, the director works against a builder interface and can drive several concrete builders with the same recipe: one that assembles the class and another that produces, say, the whiteboard poster. There, the client picks the concrete builder, hands it to the director and finally asks the builder for the result; here SessionTemplates creates the builder and returns the session, which is simpler. In Java, the most common form is what you see here, a fluent builder inside the class (the Effective Java style), with or without a director.
Step 7 of 9
Hyrox prep in the app
The coach sends POST /api/sessions with a name, a time, a coach and "beginner-friendly", but no length or spots.
SessionControllerpasses the request toScheduleService.- The service creates the builder with the essentials and only calls the methods for the fields present in the request.
build()validates, and the service saves the class with 60 minutes and 12 spots, the defaults.
Step 8 of 9
Spring already does it for you
Spring is full of builders. The most useful one day to day is RestClient.Builder: Spring Boot injects it already configured (message converters, customizers) and with prototype scope, so every injection point gets a new one. You add your baseUrl and headers, call build() and you have your client.
There are more in the example itself: the controller builds the Location header with ServletUriComponentsBuilder and answers with ResponseEntity.created(location).body(...), which is a builder too. And in the tests, the MockHttpServletRequestBuilder that post(...) returns.
Step 9 of 9
Recap
You started with seven arguments in a row and ended up with:
- A builder created with the essentials, holding the defaults.
- Named methods for every option, chainable.
build(), which hands over an immutable, validated object.
And when not to use it: if the object has three or four fields and almost all are required, a record with its constructor (or a named static method) is enough.
- An optional director for the recipes you repeat.
Code
TelescopingSession.java
public TelescopingSession(String name, LocalTime startsAt) {
this(name, startsAt, 60);
}
public TelescopingSession(String name, LocalTime startsAt, int minutes) {
this(name, startsAt, minutes, 12);
}
public TelescopingSession(String name, LocalTime startsAt, int minutes, int capacity) {
this(name, startsAt, minutes, capacity, null, false, false);
}
public static TelescopingSession hyroxPrep() {
return new TelescopingSession("Hyrox prep", LocalTime.of(18, 0), 60, 12, "Ana", true, false);
}MutableSession.java
public static MutableSession hyroxPrep() {
MutableSession s = new MutableSession(); // exists already, with no name and no time
s.setName("Hyrox prep");
s.setStartsAt(LocalTime.of(18, 0));
s.setCoach("Ana");
s.setBeginnerFriendly(true);
return s; // forget a line and nobody notices
}
public void setCapacity(int capacity) {
this.capacity = capacity; // 0? -3? accepted
}ClassSession.java
/** What every class needs goes in here; everything else has a sensible default. */
public static Builder builder(String name, LocalTime startsAt) {
return new Builder(name, startsAt);
}
public static final class Builder {
private final String name;
private final LocalTime startsAt;
private int minutes = 60;
private int capacity = 12;
private String coach;
private boolean beginnerFriendly;
private boolean waitlist;
private Builder(String name, LocalTime startsAt) {
this.name = name;
this.startsAt = startsAt;
}
public Builder minutes(int minutes) { this.minutes = minutes; return this; }
public Builder capacity(int capacity) { this.capacity = capacity; return this; }
public Builder coach(String coach) { this.coach = coach; return this; }
public Builder beginnerFriendly() { this.beginnerFriendly = true; return this; }
public Builder waitlist() { this.waitlist = true; return this; }
public ClassSession build() {
return new ClassSession(name, startsAt, minutes, capacity, coach, beginnerFriendly, waitlist);
}
}ClassSessionTest.java
ClassSession hyrox = ClassSession.builder("Hyrox prep", LocalTime.of(18, 0))
.coach("Ana")
.beginnerFriendly()
.build();ClassSession.java
public ClassSession {
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
name = name.strip();
if (name.length() > 60) throw new IllegalArgumentException("name is at most 60 characters");
if (startsAt == null) throw new IllegalArgumentException("start time is required");
if (minutes < 15 || minutes > 120 || minutes % 15 != 0) {
throw new IllegalArgumentException("minutes must be 15 to 120, in steps of 15");
}
if (capacity < 1 || capacity > 30) {
throw new IllegalArgumentException("capacity must be between 1 and 30");
}
if (coach != null) {
if (coach.isBlank()) throw new IllegalArgumentException("coach cannot be blank");
coach = coach.strip();
if (coach.length() > 40) throw new IllegalArgumentException("coach is at most 40 characters");
}
if (beginnerFriendly && coach == null) {
throw new IllegalArgumentException("a beginner-friendly class needs a coach");
}
}SessionTemplates.java
public ClassSession build(String template, LocalTime startsAt, String coach) {
String key = template == null ? "" : template.strip().toLowerCase(Locale.ROOT);
return switch (key) {
case "beginner" -> ClassSession.builder("Beginners", startsAt)
.minutes(75).capacity(8).coach(coach)
.beginnerFriendly().waitlist()
.build();
case "open-gym" -> {
if (coach != null) throw new IllegalArgumentException("an open gym has no coach");
yield ClassSession.builder("Open gym", startsAt)
.minutes(120).capacity(20)
.build();
}
default -> throw new IllegalArgumentException("unknown template: " + abbreviate(template));
};
}ScheduleService.java
public Scheduled schedule(SessionRequest req) {
ClassSession.Builder b = ClassSession.builder(req.name(), req.startsAt());
if (req.minutes() != null) b.minutes(req.minutes()); // only what the coach sent;
if (req.capacity() != null) b.capacity(req.capacity()); // the rest keeps its default
if (req.coach() != null) b.coach(req.coach());
if (Boolean.TRUE.equals(req.beginnerFriendly())) b.beginnerFriendly();
if (Boolean.TRUE.equals(req.waitlist())) b.waitlist();
return save(b.build()); // build() rejects an impossible class
}SpringDoesItTooTest.java
RestClient leaderboard = builder // injected by Spring Boot, already configured
.baseUrl("https://leaderboard.example")
.defaultHeader("X-Box", "patterns2learn")
.build();
String top = leaderboard.get().uri("/wods/{wod}/top", "fran").retrieve().body(String.class);ClassSession.java
/** What every class needs goes in here; everything else has a sensible default. */
public static Builder builder(String name, LocalTime startsAt) {
return new Builder(name, startsAt);
}
public static final class Builder {
private final String name;
private final LocalTime startsAt;
private int minutes = 60;
private int capacity = 12;
private String coach;
private boolean beginnerFriendly;
private boolean waitlist;
private Builder(String name, LocalTime startsAt) {
this.name = name;
this.startsAt = startsAt;
}
public Builder minutes(int minutes) { this.minutes = minutes; return this; }
public Builder capacity(int capacity) { this.capacity = capacity; return this; }
public Builder coach(String coach) { this.coach = coach; return this; }
public Builder beginnerFriendly() { this.beginnerFriendly = true; return this; }
public Builder waitlist() { this.waitlist = true; return this; }
public ClassSession build() {
return new ClassSession(name, startsAt, minutes, capacity, coach, beginnerFriendly, waitlist);
}
}