Builder: Step by Step, Then Build
When a shipment is made with a constructor of nine arguments, half of them false or empty, nobody can read a call and a swapped pair compiles fine; a builder names each step, leaves out what you don't need, and checks the whole thing once, when you build.
Apprentice · OOP · Updated
After this lesson you can
- Build an object with many optional parts step by step, with a builder that names each step
- Spot the smells that point to Builder: a constructor with a long list of arguments, many of them empty
Key takeaways
- The smell: a constructor with a long list of arguments, many of them false or empty, that nobody can read at the call.
- The cause: one call has to say everything about the object at once, by position, even the parts it doesn't need.
- The fix: a builder with one named step for each part; you call only the steps you need, then build.
- The builder's build step is one place to check the finished object before anyone uses it.
Before this: Meet the Package Tracker, and classes with a constructor.
Lakeside Parcel's customers can now add extras to a shipment: insurance ($3), signature required ($2), a pickup window (morning or afternoon, free) and gift wrap ($4). Each shipment also has its package number, who it's for, their address, a carrier and a weight. That's nine things to say about one shipment, and most shipments use only a few of the extras. This lesson ends with a pattern called Builder, but first, here's what nine things in one call does to the code.
The symptom: nine arguments, and nobody can read them
A shipment is made in one call to its constructor, with all nine values in order. The checkout screen made Maya's; the phone desk made Sam's:
// The checkout screen: Maya asked for insurance and gift wrap.
Shipment maya = new Shipment(42, "Maya", "Oak Ave", "QuickShip", 5, true, false, null, true);
// The phone desk: Sam asked for insurance and a morning pickup.
Shipment sam = new Shipment(43, "Sam", "Pine Rd", "EcoFreight", 2, false, true, "morning", false);
Console.WriteLine(maya.Describe());
Console.WriteLine(sam.Describe());
class Shipment
{
private readonly int id, pounds;
private readonly string recipient, address, carrier;
private readonly bool insurance, signature, giftWrap;
private readonly string? pickupWindow;
public Shipment(int id, string recipient, string address, string carrier, int pounds,
bool insurance, bool signature, string? pickupWindow, bool giftWrap)
{
this.id = id; this.recipient = recipient; this.address = address; this.carrier = carrier; this.pounds = pounds;
this.insurance = insurance; this.signature = signature; this.pickupWindow = pickupWindow; this.giftWrap = giftWrap;
}
public string Describe()
{
List<string> extras = new List<string>();
int cost = 0;
if (insurance) { extras.Add("insurance"); cost += 3; }
if (signature) { extras.Add("signature required"); cost += 2; }
if (pickupWindow != null) { extras.Add(pickupWindow + " pickup"); }
if (giftWrap) { extras.Add("gift wrap"); cost += 4; }
return quot;Package {id}, {pounds} lb, to {recipient} at {address} by {carrier}: {string.Join(", ", extras)} (${cost} extra)";
}
}
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: signature required, morning pickup ($2 extra)
class Shipment {
private final int id, pounds;
private final String recipient, address, carrier, pickupWindow;
private final boolean insurance, signature, giftWrap;
Shipment(int id, String recipient, String address, String carrier, int pounds,
boolean insurance, boolean signature, String pickupWindow, boolean giftWrap) {
this.id = id; this.recipient = recipient; this.address = address; this.carrier = carrier; this.pounds = pounds;
this.insurance = insurance; this.signature = signature; this.pickupWindow = pickupWindow; this.giftWrap = giftWrap;
}
String describe() {
List<String> extras = new ArrayList<>();
int cost = 0;
if (insurance) { extras.add("insurance"); cost += 3; }
if (signature) { extras.add("signature required"); cost += 2; }
if (pickupWindow != null) { extras.add(pickupWindow + " pickup"); }
if (giftWrap) { extras.add("gift wrap"); cost += 4; }
return "Package " + id + ", " + pounds + " lb, to " + recipient + " at " + address + " by " + carrier + ": "
+ String.join(", ", extras) + " ( quot; + cost + " extra)";
}
}
void main() {
// The checkout screen: Maya asked for insurance and gift wrap.
Shipment maya = new Shipment(42, "Maya", "Oak Ave", "QuickShip", 5, true, false, null, true);
// The phone desk: Sam asked for insurance and a morning pickup.
Shipment sam = new Shipment(43, "Sam", "Pine Rd", "EcoFreight", 2, false, true, "morning", false);
IO.println(maya.describe());
IO.println(sam.describe());
}
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: signature required, morning pickup ($2 extra)
class Shipment:
def __init__(self, package_id, recipient, address, carrier, pounds, insurance, signature, pickup_window, gift_wrap):
self.package_id = package_id
self.recipient = recipient
self.address = address
self.carrier = carrier
self.pounds = pounds
self.insurance = insurance
self.signature = signature
self.pickup_window = pickup_window
self.gift_wrap = gift_wrap
def describe(self):
extras, cost = [], 0
if self.insurance:
extras.append("insurance")
cost += 3
if self.signature:
extras.append("signature required")
cost += 2
if self.pickup_window is not None:
extras.append(self.pickup_window + " pickup")
if self.gift_wrap:
extras.append("gift wrap")
cost += 4
return (f"Package {self.package_id}, {self.pounds} lb, to {self.recipient} at {self.address} "
f"by {self.carrier}: {', '.join(extras)} (${cost} extra)")
# The checkout screen: Maya asked for insurance and gift wrap.
maya = Shipment(42, "Maya", "Oak Ave", "QuickShip", 5, True, False, None, True)
# The phone desk: Sam asked for insurance and a morning pickup.
sam = Shipment(43, "Sam", "Pine Rd", "EcoFreight", 2, False, True, "morning", False)
print(maya.describe())
print(sam.describe())
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: signature required, morning pickup ($2 extra)
class Shipment {
constructor(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap) {
this.id = id;
this.recipient = recipient;
this.address = address;
this.carrier = carrier;
this.pounds = pounds;
this.insurance = insurance;
this.signature = signature;
this.pickupWindow = pickupWindow;
this.giftWrap = giftWrap;
}
describe() {
const extras = [];
let cost = 0;
if (this.insurance) { extras.push("insurance"); cost += 3; }
if (this.signature) { extras.push("signature required"); cost += 2; }
if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} (${cost} extra)`;
}
}
// The checkout screen: Maya asked for insurance and gift wrap.
const maya = new Shipment(42, "Maya", "Oak Ave", "QuickShip", 5, true, false, null, true);
// The phone desk: Sam asked for insurance and a morning pickup.
const sam = new Shipment(43, "Sam", "Pine Rd", "EcoFreight", 2, false, true, "morning", false);
console.log(maya.describe());
console.log(sam.describe());
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: signature required, morning pickup ($2 extra)
class Shipment {
id: number;
recipient: string;
address: string;
carrier: string;
pounds: number;
insurance: boolean;
signature: boolean;
pickupWindow: string | null;
giftWrap: boolean;
constructor(id: number, recipient: string, address: string, carrier: string, pounds: number,
insurance: boolean, signature: boolean, pickupWindow: string | null, giftWrap: boolean) {
this.id = id;
this.recipient = recipient;
this.address = address;
this.carrier = carrier;
this.pounds = pounds;
this.insurance = insurance;
this.signature = signature;
this.pickupWindow = pickupWindow;
this.giftWrap = giftWrap;
}
describe(): string {
const extras: string[] = [];
let cost = 0;
if (this.insurance) { extras.push("insurance"); cost += 3; }
if (this.signature) { extras.push("signature required"); cost += 2; }
if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} (${cost} extra)`;
}
}
// The checkout screen: Maya asked for insurance and gift wrap.
const maya = new Shipment(42, "Maya", "Oak Ave", "QuickShip", 5, true, false, null, true);
// The phone desk: Sam asked for insurance and a morning pickup.
const sam = new Shipment(43, "Sam", "Pine Rd", "EcoFreight", 2, false, true, "morning", false);
console.log(maya.describe());
console.log(sam.describe());
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: signature required, morning pickup ($2 extra)
Look at Sam's line. He asked for insurance, and he got a signature instead. Whoever wrote the phone desk swapped false, true, and nothing complained: two true-or-false values look exactly alike to the compiler. Read the call out loud, false, true, "morning", false, and you can't tell which is which without opening the class. When a tenth thing arrives (a "fragile" sticker, say), every call in the app gets one more value, in the right place.
- The symptom: a constructor with a long list of arguments, many of them
falseor empty, that nobody can read at the call. This smell has its own name: a long parameter list. - The cause: one call has to say everything about the shipment at once, by position, even the extras it doesn't use.
What would you try?
A comment beside each value: /* insurance */ false. It helps the reader, but nothing checks it. A comment next to the wrong value is worse than none.
A constructor for each combination: one with insurance, one with insurance and gift wrap, and so on. Four extras make sixteen combinations, and the fifth extra doubles them.
An empty new Shipment(), then set each field afterward. The calls read well, but for a while the shipment is half made: no address yet, or a pickup window of "evening". Nothing says when it's finished, and nothing checks it.
What we want is all three good parts at once: each value named where it's given, only the extras you need, and one moment when the shipment is finished and checked.
The fix: step by step, then build
A sandwich counter works this way. You move down the line: bread, then the filling, then the toppings, then the sauce. At each station you say one thing, by name, and you skip the stations you don't want. At the end of the line, the register wraps the sandwich and hands it over, finished.

In code, the counter is a second class, ShipmentBuilder. You start it with what every shipment needs (the package number, who it's for and where), then call a named step for each extra you want. Each step returns the builder itself, so the steps chain one after another. The last step, build, checks the choices and hands back the finished Shipment. The constructor with nine arguments is still there, but only the builder calls it.


Shipment maya = new ShipmentBuilder(42, "Maya", "Oak Ave")
.By("QuickShip")
.Weighing(5)
.WithInsurance()
.WithGiftWrap()
.Build();
Shipment sam = new ShipmentBuilder(43, "Sam", "Pine Rd")
.By("EcoFreight")
.Weighing(2)
.WithInsurance()
.PickUpIn("morning")
.Build();
Console.WriteLine(maya.Describe());
Console.WriteLine(sam.Describe());
// A step for each part, then build.
class ShipmentBuilder
{
private readonly int id;
private readonly string recipient, address;
private string carrier = "QuickShip";
private int pounds = 1;
private bool insurance, signature, giftWrap;
private string? pickupWindow;
public ShipmentBuilder(int id, string recipient, string address)
{
this.id = id; this.recipient = recipient; this.address = address;
}
public ShipmentBuilder By(string carrier) { this.carrier = carrier; return this; }
public ShipmentBuilder Weighing(int pounds) { this.pounds = pounds; return this; }
public ShipmentBuilder WithInsurance() { insurance = true; return this; }
public ShipmentBuilder WithSignature() { signature = true; return this; }
public ShipmentBuilder PickUpIn(string window) { pickupWindow = window; return this; }
public ShipmentBuilder WithGiftWrap() { giftWrap = true; return this; }
public Shipment Build()
{
if (pickupWindow != null && pickupWindow != "morning" && pickupWindow != "afternoon")
{
throw new ArgumentException( quot;A pickup window is morning or afternoon, not {pickupWindow}.");
}
return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap);
}
}
class Shipment
{
private readonly int id, pounds;
private readonly string recipient, address, carrier;
private readonly bool insurance, signature, giftWrap;
private readonly string? pickupWindow;
public Shipment(int id, string recipient, string address, string carrier, int pounds,
bool insurance, bool signature, string? pickupWindow, bool giftWrap)
{
this.id = id; this.recipient = recipient; this.address = address; this.carrier = carrier; this.pounds = pounds;
this.insurance = insurance; this.signature = signature; this.pickupWindow = pickupWindow; this.giftWrap = giftWrap;
}
public string Describe()
{
List<string> extras = new List<string>();
int cost = 0;
if (insurance) { extras.Add("insurance"); cost += 3; }
if (signature) { extras.Add("signature required"); cost += 2; }
if (pickupWindow != null) { extras.Add(pickupWindow + " pickup"); }
if (giftWrap) { extras.Add("gift wrap"); cost += 4; }
return quot;Package {id}, {pounds} lb, to {recipient} at {address} by {carrier}: {string.Join(", ", extras)} (${cost} extra)";
}
}
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
// A step for each part, then build.
class ShipmentBuilder {
private final int id;
private final String recipient, address;
private String carrier = "QuickShip";
private int pounds = 1;
private boolean insurance, signature, giftWrap;
private String pickupWindow = null;
ShipmentBuilder(int id, String recipient, String address) {
this.id = id; this.recipient = recipient; this.address = address;
}
ShipmentBuilder by(String carrier) { this.carrier = carrier; return this; }
ShipmentBuilder weighing(int pounds) { this.pounds = pounds; return this; }
ShipmentBuilder withInsurance() { insurance = true; return this; }
ShipmentBuilder withSignature() { signature = true; return this; }
ShipmentBuilder pickUpIn(String window) { pickupWindow = window; return this; }
ShipmentBuilder withGiftWrap() { giftWrap = true; return this; }
Shipment build() {
if (pickupWindow != null && !pickupWindow.equals("morning") && !pickupWindow.equals("afternoon")) {
throw new IllegalArgumentException("A pickup window is morning or afternoon, not " + pickupWindow + ".");
}
return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap);
}
}
class Shipment {
private final int id, pounds;
private final String recipient, address, carrier, pickupWindow;
private final boolean insurance, signature, giftWrap;
Shipment(int id, String recipient, String address, String carrier, int pounds,
boolean insurance, boolean signature, String pickupWindow, boolean giftWrap) {
this.id = id; this.recipient = recipient; this.address = address; this.carrier = carrier; this.pounds = pounds;
this.insurance = insurance; this.signature = signature; this.pickupWindow = pickupWindow; this.giftWrap = giftWrap;
}
String describe() {
List<String> extras = new ArrayList<>();
int cost = 0;
if (insurance) { extras.add("insurance"); cost += 3; }
if (signature) { extras.add("signature required"); cost += 2; }
if (pickupWindow != null) { extras.add(pickupWindow + " pickup"); }
if (giftWrap) { extras.add("gift wrap"); cost += 4; }
return "Package " + id + ", " + pounds + " lb, to " + recipient + " at " + address + " by " + carrier + ": "
+ String.join(", ", extras) + " ( quot; + cost + " extra)";
}
}
void main() {
Shipment maya = new ShipmentBuilder(42, "Maya", "Oak Ave")
.by("QuickShip")
.weighing(5)
.withInsurance()
.withGiftWrap()
.build();
Shipment sam = new ShipmentBuilder(43, "Sam", "Pine Rd")
.by("EcoFreight")
.weighing(2)
.withInsurance()
.pickUpIn("morning")
.build();
IO.println(maya.describe());
IO.println(sam.describe());
}
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
class Shipment:
def __init__(self, package_id, recipient, address, carrier, pounds, insurance, signature, pickup_window, gift_wrap):
self.package_id = package_id
self.recipient = recipient
self.address = address
self.carrier = carrier
self.pounds = pounds
self.insurance = insurance
self.signature = signature
self.pickup_window = pickup_window
self.gift_wrap = gift_wrap
def describe(self):
extras, cost = [], 0
if self.insurance:
extras.append("insurance")
cost += 3
if self.signature:
extras.append("signature required")
cost += 2
if self.pickup_window is not None:
extras.append(self.pickup_window + " pickup")
if self.gift_wrap:
extras.append("gift wrap")
cost += 4
return (f"Package {self.package_id}, {self.pounds} lb, to {self.recipient} at {self.address} "
f"by {self.carrier}: {', '.join(extras)} (${cost} extra)")
# A step for each part, then build.
class ShipmentBuilder:
def __init__(self, package_id, recipient, address):
self.package_id = package_id
self.recipient = recipient
self.address = address
self.carrier = "QuickShip"
self.pounds = 1
self.insurance = False
self.signature = False
self.pickup_window = None
self.gift_wrap = False
def by(self, carrier):
self.carrier = carrier
return self
def weighing(self, pounds):
self.pounds = pounds
return self
def with_insurance(self):
self.insurance = True
return self
def with_signature(self):
self.signature = True
return self
def pick_up_in(self, window):
self.pickup_window = window
return self
def with_gift_wrap(self):
self.gift_wrap = True
return self
def build(self):
if self.pickup_window not in (None, "morning", "afternoon"):
raise ValueError(f"A pickup window is morning or afternoon, not {self.pickup_window}.")
return Shipment(self.package_id, self.recipient, self.address, self.carrier, self.pounds,
self.insurance, self.signature, self.pickup_window, self.gift_wrap)
maya = (ShipmentBuilder(42, "Maya", "Oak Ave")
.by("QuickShip")
.weighing(5)
.with_insurance()
.with_gift_wrap()
.build())
sam = (ShipmentBuilder(43, "Sam", "Pine Rd")
.by("EcoFreight")
.weighing(2)
.with_insurance()
.pick_up_in("morning")
.build())
print(maya.describe())
print(sam.describe())
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
class Shipment {
constructor(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap) {
this.id = id;
this.recipient = recipient;
this.address = address;
this.carrier = carrier;
this.pounds = pounds;
this.insurance = insurance;
this.signature = signature;
this.pickupWindow = pickupWindow;
this.giftWrap = giftWrap;
}
describe() {
const extras = [];
let cost = 0;
if (this.insurance) { extras.push("insurance"); cost += 3; }
if (this.signature) { extras.push("signature required"); cost += 2; }
if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} (${cost} extra)`;
}
}
// A step for each part, then build.
class ShipmentBuilder {
#carrier = "QuickShip";
#pounds = 1;
#insurance = false;
#signature = false;
#pickupWindow = null;
#giftWrap = false;
constructor(id, recipient, address) {
this.id = id;
this.recipient = recipient;
this.address = address;
}
by(carrier) { this.#carrier = carrier; return this; }
weighing(pounds) { this.#pounds = pounds; return this; }
withInsurance() { this.#insurance = true; return this; }
withSignature() { this.#signature = true; return this; }
pickUpIn(window) { this.#pickupWindow = window; return this; }
withGiftWrap() { this.#giftWrap = true; return this; }
build() {
if (this.#pickupWindow !== null && this.#pickupWindow !== "morning" && this.#pickupWindow !== "afternoon") {
throw new Error(`A pickup window is morning or afternoon, not ${this.#pickupWindow}.`);
}
return new Shipment(this.id, this.recipient, this.address, this.#carrier, this.#pounds,
this.#insurance, this.#signature, this.#pickupWindow, this.#giftWrap);
}
}
const maya = new ShipmentBuilder(42, "Maya", "Oak Ave")
.by("QuickShip")
.weighing(5)
.withInsurance()
.withGiftWrap()
.build();
const sam = new ShipmentBuilder(43, "Sam", "Pine Rd")
.by("EcoFreight")
.weighing(2)
.withInsurance()
.pickUpIn("morning")
.build();
console.log(maya.describe());
console.log(sam.describe());
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
class Shipment {
id: number;
recipient: string;
address: string;
carrier: string;
pounds: number;
insurance: boolean;
signature: boolean;
pickupWindow: string | null;
giftWrap: boolean;
constructor(id: number, recipient: string, address: string, carrier: string, pounds: number,
insurance: boolean, signature: boolean, pickupWindow: string | null, giftWrap: boolean) {
this.id = id;
this.recipient = recipient;
this.address = address;
this.carrier = carrier;
this.pounds = pounds;
this.insurance = insurance;
this.signature = signature;
this.pickupWindow = pickupWindow;
this.giftWrap = giftWrap;
}
describe(): string {
const extras: string[] = [];
let cost = 0;
if (this.insurance) { extras.push("insurance"); cost += 3; }
if (this.signature) { extras.push("signature required"); cost += 2; }
if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} (${cost} extra)`;
}
}
// A step for each part, then build.
class ShipmentBuilder {
#id: number;
#recipient: string;
#address: string;
#carrier = "QuickShip";
#pounds = 1;
#insurance = false;
#signature = false;
#pickupWindow: string | null = null;
#giftWrap = false;
constructor(id: number, recipient: string, address: string) {
this.#id = id;
this.#recipient = recipient;
this.#address = address;
}
by(carrier: string): ShipmentBuilder { this.#carrier = carrier; return this; }
weighing(pounds: number): ShipmentBuilder { this.#pounds = pounds; return this; }
withInsurance(): ShipmentBuilder { this.#insurance = true; return this; }
withSignature(): ShipmentBuilder { this.#signature = true; return this; }
pickUpIn(window: string): ShipmentBuilder { this.#pickupWindow = window; return this; }
withGiftWrap(): ShipmentBuilder { this.#giftWrap = true; return this; }
build(): Shipment {
if (this.#pickupWindow !== null && this.#pickupWindow !== "morning" && this.#pickupWindow !== "afternoon") {
throw new Error(`A pickup window is morning or afternoon, not ${this.#pickupWindow}.`);
}
return new Shipment(this.#id, this.#recipient, this.#address, this.#carrier, this.#pounds,
this.#insurance, this.#signature, this.#pickupWindow, this.#giftWrap);
}
}
const maya = new ShipmentBuilder(42, "Maya", "Oak Ave")
.by("QuickShip")
.weighing(5)
.withInsurance()
.withGiftWrap()
.build();
const sam = new ShipmentBuilder(43, "Sam", "Pine Rd")
.by("EcoFreight")
.weighing(2)
.withInsurance()
.pickUpIn("morning")
.build();
console.log(maya.describe());
console.log(sam.describe());
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Sam's line is right now: insurance and a morning pickup, $3. The phone desk's call says .WithInsurance() in words, so there's nothing to swap. A shipment with no extras is new ShipmentBuilder(44, "Leo", "Cedar Ln").Build(), with the carrier and the weight left at the builder's defaults. And the tenth extra, the "fragile" sticker, is one new step on the builder; no call that doesn't want it has to change.
The build step is also the one place to check the whole shipment. Ask for an "evening" pickup and build refuses, so a shipment that breaks a rule never exists.
Where the languages differ. Each step ends with return this (return self in Python), so the next step can be called on what it hands back; this is called method chaining. Python needs the chain inside parentheses to spread it over several lines. TypeScript's builder keeps its choices in #private fields, so nothing outside can change them halfway.
How it got its name
The builder builds the object one step at a time and hands it over when you ask for it. Teams kept writing this same helper for objects with many optional parts, so it got a name: the Builder pattern.
In your textbook: the original 1994 book's Builder has one more role, a director that runs the same steps on different builders to make different things (a shipping label and a customs form from the same shipment, say). The version above, a builder you call step by step, is the one you'll meet most in code today.
Where you've already used it
StringBuilderin C# and Java:Appendpiece by piece, thenToString()once.- Java's
HttpRequest.newBuilder().uri(...).header(...).build(). - ASP.NET Core's
WebApplication.CreateBuilder(args): set the app up step by step, thenbuilder.Build().
When not to use it
- When there are a few arguments and all of them are needed.
new Box(5)doesn't need a builder. - When your language already names arguments. C#, Python, JavaScript and TypeScript can do most of this without a builder class; that's the next lesson.
- When the object never varies. A builder for a thing that's always made the same way is a second class to read for nothing.
The cost: a second class that repeats every field of the first, and has to be kept in step with it when a field is added.
How often you'll meet it: now and then in app code, and every day in the libraries you use (our estimate).
Check yourself
2 questions to try on the lesson page.
So what
When a constructor's arguments can't be read at the call, and most of them are "no thanks", give each part a named step and build at the end. The call says what it means, and the finished object is checked once.