AlgoViz

Encapsulation

easy 35 min

Put 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

DesignReadDepositMemory for 1,000,000 entries of 16 bytes
One number1 step1 step8 bytes, no history
Entries, sum on read1,000,000 steps1 stepabout 16 MB
Entries and total1 step2 stepsabout 16 MB plus 8 bytes
Total plus entries in a database1 step1 transaction8 bytes here
All four fit behind the same two methods, so this decision can be made late, and again. A Python object per entry costs more than 16 bytes, so measure.

Failure walk

It fails whenVisible asAnswer
append succeeds, then the process dies before the totaltotal is too small after restartstore entries, rebuild the total at start
two threads append at oncetwo entries with the same numberone private lock around both writes
someone subclassed V1 and used _balance_centsAttributeError after the swapfinal class, or treat protected as public
a report reads the database table directlyreport breaks, code is finethe table was a second public interface