Encapsulation: public fields to guarded state
Make one class own its data, so every change follows the same rules.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–9Payoff
Steps 10–11Recap
Steps 12–13The code: before and after
Before
class GiftCard {
constructor(
public code: string,
public balance: number,
) {}
}
class Checkout {
pay(card: GiftCard, amount: number): void {
if (card.balance >= amount) {
card.balance -= amount;
}
}
}
class Refunds {
refund(card: GiftCard, amount: number): void {
card.balance += amount;
}
}
class Support {
cancel(card: GiftCard): void {
card.balance = 0;
}
}
function shop(): string {
const card = new GiftCard("GC-7", 50);
new Checkout().pay(card, 30);
new Refunds().refund(card, 10);
new Support().cancel(card);
return String(card.balance);
}After
class GiftCard {
#balance: number;
readonly #history: string[] = [];
constructor(public code: string, balance: number) {
this.#balance = balance;
}
get balance(): number {
return this.#balance;
}
get history(): readonly string[] {
return [...this.#history];
}
charge(amount: number): boolean {
if (this.#balance >= amount) {
this.#balance -= amount;
this.#history.push(`paid ${amount}`);
return true;
}
return false;
}
credit(amount: number): void {
this.#balance += amount;
this.#history.push(`refunded ${amount}`);
}
cancel(): void {
this.#history.push(`cancelled ${this.#balance}`);
this.#balance = 0;
}
}
class Checkout {
pay(card: GiftCard, amount: number): void {
card.charge(amount);
}
}
class Refunds {
refund(card: GiftCard, amount: number): void {
card.credit(amount);
}
}
class Support {
cancel(card: GiftCard): void {
card.cancel();
}
}
function shop(): string {
const card = new GiftCard("GC-7", 50);
new Checkout().pay(card, 30);
new Refunds().refund(card, 10);
new Support().cancel(card);
return `${card.balance} ${card.history.join(", ")}`;
}Transcript, step by step
Problem
Step 1: A shop's gift cards Before
A gift card here holds a code and a balance, and both are public fields. Checkout takes money off when there's enough, Refunds puts money back, and Support cancels a card by setting the balance to zero. The card starts at 50, pays 30, gets 10 back, and is cancelled, so shop returns 0.
Step 2: Finance wants a history Code smell
Finance now needs a history of every balance change, for audits. The quick way is a public history array on the card, plus a line in pay and a line in refund that record each change. Shop then returns the balance, followed by the history.
Step 3: Every class writes the balance Code smell
A public field lets any class change the balance, so the rule for changing it is spread over every class that writes it. Checkout writes the balance here, Refunds here, and Support here. Support's cancel takes 30 off the card, and the history never hears of it, so the audit shows 30 left on a card that holds 0. And the funds check lives in Checkout only, so Refunds and Support write the balance with no check at all.
Refactor
Step 4: Refactor first Back it out
Let's take the history out again. We'll refactor first, so that adding the history becomes a small change, and then we'll add it.
Step 5: Hide the balance Encapsulate Field
First, the balance moves into a private field, with a getter and a setter named balance on Gift Card. The hash makes the field private, so the compiler, and the runtime too, reject any use of it outside Gift Card. Checkout, Refunds and Support run unchanged, but every write they make now goes through the setter. The field is hidden, but any class can still set any number, so this alone guards nothing.
Step 6: Charge moves into the card Move Method
The funds check and the subtraction move into Gift Card, as a method called charge. Charge returns true when the card had enough, and false when it didn't. Checkout now calls card dot charge with the amount, and the card still ends at 0.
Step 7: Credit moves into the card Move Method
The refund's addition moves into Gift Card the same way, as a method called credit. Refunds now calls card dot credit, and it no longer reads or writes the balance itself.
Step 8: Cancel moves into the card Move Method
Support's zeroing moves in last, as cancel, a method with no parameters. Support calls card dot cancel, so no class outside Gift Card uses the setter any more.
Step 9: Delete the setter Remove Setting Method
Nothing outside Gift Card writes the balance now, so the setter goes, and only the getter stays for shop to read. From here on, the compiler rejects any outside write to balance, because a getter alone makes it a read-only property. The balance now changes only inside Gift Card, through charge, credit and cancel. That is encapsulation, where an object keeps its fields private and offers methods for the changes it allows, so its state can only change in one place.
Payoff
Step 10: Add the history again Payoff
Now the history goes back in, as a private array inside Gift Card. Charge, credit and cancel each add one line to it. The history getter returns a copy typed as a read-only array, so callers can read the list but can't add to it, and that move is called Encapsulate Collection. Checkout, Refunds and Support didn't change, and shop only gains the history in what it returns.
Step 11: One owner for the balance Payoff
The three writes are gone from the callers, so Checkout calls charge here, Refunds calls credit here, and Support calls cancel here. Cancel now records cancelled 30 before it zeroes the card, so the history and the balance agree. And the funds check sits next to the only code that writes the balance.
Recap
Step 12: Where we started, where we ended Before / after
On the left, the balance is a public field, and Checkout, Refunds and Support each write it themselves. On the right, the balance is private, and only charge, credit and cancel change it. A caller like Checkout makes one call, and the card decides what happens to its money.
Step 13: When to reach for it Takeaways
Reach for it when several classes change the same value and a rule must hold every time it changes. Skip it when a type only carries data with no rule, like a DTO for one view, because accessors there add lines and protect nothing. You'll spot the need by the same field assigned in many classes, or by a check copied before each write. A built-in Map works this way, because you can read its size, but only set, delete and clear can change it.