Immutability: value objects instead of setters
Share small objects like prices safely, so one change never leaks into another.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–6Payoff
Steps 7–8TypeScript bonus
Step 9Recap
Steps 10–11The code: before and after
Before
class Price {
constructor(
private amount: number,
private currency: string,
) {}
getAmount(): number {
return this.amount;
}
getCurrency(): string {
return this.currency;
}
setAmount(amount: number): void {
this.amount = amount;
}
}
class Booking {
constructor(
private readonly car: string,
private price: Price,
) {}
line(): string {
const amount = this.price.getAmount();
const currency = this.price.getCurrency();
return `${this.car}: ${amount} ${currency}`;
}
sameRateAs(other: Booking): boolean {
return this.price === other.price;
}
}
const weekend = new Price(120, "USD");
const ana = new Booking("Golf", weekend);
const ben = new Booking("Polo", weekend);
const same = ana.sameRateAs(ben);
const output = [ana.line(), ben.line(), String(same)];After
class Price {
constructor(
readonly amount: number,
readonly currency: string,
) {}
plus(extra: number): Price {
return new Price(this.amount + extra, this.currency);
}
equals(other: Price): boolean {
return (
this.amount === other.amount &&
this.currency === other.currency
);
}
}
class Booking {
constructor(
private readonly car: string,
private price: Price,
) {}
line(): string {
const { amount, currency } = this.price;
return `${this.car}: ${amount} ${currency}`;
}
sameRateAs(other: Booking): boolean {
return this.price.equals(other.price);
}
addExtra(extra: number): void {
this.price = this.price.plus(extra);
}
}
const weekend = new Price(120, "USD");
const ana = new Booking("Golf", weekend);
const ben = new Booking("Polo", weekend);
ana.addExtra(15);
const same = ana.sameRateAs(ben);
const output = [ana.line(), ben.line(), String(same)];Transcript, step by step
Problem
Step 1: One weekend rate Before
This is the same car rental desk that sent receipts last time, and today it prices bookings. A Price holds an amount and a currency, and it has a setter, a method that changes one field, here set amount. A Booking holds a car and a price, builds one line, and checks whether two bookings pay the same rate by asking if they hold the same Price object. The desk makes one weekend rate and gives it to two customers, Ana and Ben, so the output holds Golf and Polo at a hundred twenty dollars each, then true. Both bookings cost the same, so making the weekend price once and passing it to both looked like the obvious choice.
Step 2: Ana adds a child seat Code smell
Ana adds a child seat for fifteen dollars. The quick way gives Booking an add extra method that reads the amount and sets it fifteen higher. Ana's line now says a hundred thirty five, but Ben's line says a hundred thirty five as well, and Ben never asked for a seat.
Step 3: A shared mutable price Code smell
A mutable object is one whose fields can change after it is made, and a shared reference is two variables that point at the same object. Put them together and you get a shared mutable price, so a setter called through one booking changes the price the other booking reads. You can see it in the setter call here, in Ana's booking here, and in Ben's booking, which holds the same object, here. The bug sits in neither line alone, so to find it you have to trace every place a Price is shared. The usual workaround is to copy the Price before each change, and one forgotten copy brings the bug back.
Refactor
Step 4: Refactor first Back it out
So let's take the child seat out again. We'll refactor first, so a Price can't change under anyone, and then we'll add the seat.
Step 5: No setter, readonly fields Remove Setting Method
The first move is Remove Setting Method, so we delete set amount, and nothing called it, so the output stays the same. Both fields become readonly, so the TypeScript compiler rejects any write after the constructor, though nothing stops one at run time. That makes Price immutable, which means its fields never change after it is made.
Step 6: Equal by value Change Reference to Value
The old triple equals only said true because both bookings share one object, and two separate prices of a hundred twenty dollars would have said false. But a Price can never change now, so two prices with the same amount and currency can stand in for each other. That's a value object, a small immutable object that is equal to another when its values are equal. So the move is Change Reference to Value, and because triple equals on objects always compares references in TypeScript, Price gets an equals method that compares the amount and the currency. Same rate as now calls equals, and the output still ends in true. The desk still hands the same weekend price to both bookings, and now that's safe, because nobody can change it.
Payoff
Step 7: The child seat, again Payoff
Now the child seat comes back, and Price gets a plus method that returns a new Price with the extra added. Add extra stores that new Price in Ana's booking, and the desk calls it the same way as before. The output now holds Golf at a hundred thirty five, Polo at a hundred twenty, and false, because the two rates differ. The setter call is gone, Ana's booking now holds a new Price, and Ben's still holds the weekend one. The two weekend arguments, Ben's line and the same rate as method didn't change in this step.
Step 8: Replaced, never changed Value object
A value object is never changed, only replaced. It fits here because two bookings share the weekend Price, so replacing it in Ana's booking can't reach Ben's. The booking is different, because it's an entity, an object with its own identity whose state may change. It's Ana's booking, so its price field may point somewhere new, but the Price it points at never changes.
TypeScript bonus
Step 9: Public readonly fields TypeScript bonus
Price still spends six lines on two getters that only hand out fields it keeps private. In TypeScript, a readonly field can be public, because the compiler lets any code read it and no code write it, so the getters go. Line now takes the amount and the currency straight from the price in one destructuring line. Plus and equals stay as they were, and like before, readonly is a compile time check, so code that must also block writes at run time would add Object freeze.
Recap
Step 10: Where we started, where we ended Before / after
On the left, Price had a setter, so any booking that held it could change it for everyone. Same rate as compared references, which only worked because the bookings shared one object. On the right, Price has readonly fields, and plus returns a new Price instead of changing the old one. Ana's extra replaces the price in her booking only, and equals compares values.
Step 11: When to reach for it Takeaways
Reach for it when a small object, like a price, a date range or an address, is passed around and shared. Skip it when the object has its own identity, like Ana's booking, because code that holds it must see its changes, and a copy would leave it looking at the old booking. You'll spot it by a setter on an object that more than one owner holds, or by defensive copies before every change. TypeScript strings work this way, so to upper case returns a new string and leaves the old one alone.