Cheatsheet

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.

Structure (UML)

Spring contextSessionTemplatesSessionControllerClassSession.Builder30ClassSessionScheduleServiceCoach

Participants

  • Builder (ClassSession.Builder), which collects the pieces step by step
  • Product (ClassSession), the finished object, immutable and valid
  • Director (SessionTemplates), which knows the usual recipes and calls the steps in order
  • Client (ScheduleService), which uses the builder directly for one-off requests and leaves the fixed recipes to the director

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);
    }
}

Pros

  • Every option has a name, so the call reads on its own
  • Defaults live in one place and you only change what you need
  • The object doesn't exist until build(), and build() validates it in one place

Cons

  • More code, one extra class per product
  • If the object has two or three fields, a constructor is enough
  • A forgotten required field only shows up when you call build(), not at compile time (unless you ask for it when creating the builder)

← Builder · Run it