Encapsulation
easy 35 minPut the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.
Watch lesson4:51
Swap the inside
The balance becomes a ledger, and no caller changes. Then the numbers and the failure walk.
The point: the proof of encapsulation is a replacement. If you can swap the data structure and run the same callers and tests, the inside was really hidden.
From a number to a ledger
Support asks: why is my balance 800? One number cannot answer. We need the list of entries. The public methods stay.
Two insides, one caller
It knows two operations and nothing about storage.
from typing import NamedTuple, Protocolclass Wallet(Protocol): @property def balance_cents(self) -> int: ... def deposit(self, cents: int) -> None: ...def welcome_bonus(w: Wallet) -> str: w.deposit(500) return f"you have {w.balance_cents}"Lines 4 to 7
The public list, written down as a type. This is what must not change.
1 of 2
The cost, with numbers
| Design | Read | Deposit | Memory for 1,000,000 entries of 16 bytes |
|---|---|---|---|
| One number | 1 step | 1 step | 8 bytes, no history |
| Entries, sum on read | 1,000,000 steps | 1 step | about 16 MB |
| Entries and total | 1 step | 2 steps | about 16 MB plus 8 bytes |
| Total plus entries in a database | 1 step | 1 transaction | 8 bytes here |
Failure walk
| It fails when | Visible as | Answer |
|---|---|---|
| append succeeds, then the process dies before the total | total is too small after restart | store entries, rebuild the total at start |
| two threads append at once | two entries with the same number | one private lock around both writes |
someone subclassed V1 and used _balance_cents | AttributeError after the swap | final class, or treat protected as public |
| a report reads the database table directly | report breaks, code is fine | the table was a second public interface |