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
Verify
Trace the account by hand, then try to break it from outside.
The point: test through the public methods only. If a test needs a private field, the class is missing a question or the test is too curious.
A trace by hand
| Call | Balance | Taken today | Answer |
|---|---|---|---|
| new account | 0 | 0 | created |
deposit(100000) | 100,000 | 0 | done |
withdraw(20000, day 1) | 80,000 | 20,000 | done |
withdraw(500000, day 1) | 80,000 | 20,000 | refused: not enough money |
withdraw(40000, day 1) | 80,000 | 20,000 | refused: daily limit reached |
withdraw(40000, day 2) | 40,000 | 40,000 | done, a new day |
deposit(-100) | 40,000 | 40,000 | refused: amount must be positive |
freeze(), withdraw(1, day 3) | 40,000 | 40,000 | refused: account is frozen |
The same trace as a test
Python
class Refused(Exception): """The account said no. The message says why."""class BankAccount: DAILY_LIMIT = 50_000 def __init__(self, holder: str, number: str) -> None: if not holder.strip(): raise ValueError("holder is required") self._holder = holder.strip() self._number = number self._balance_cents = 0 self._frozen = False self._day = 0 self._taken_today = 0 @property def balance_cents(self) -> int: return self._balance_cents @property def masked_number(self) -> str: return "****" + self._number[-2:] def can_withdraw(self, cents: int, day: int) -> bool: return self._why_not(cents, day) is None def deposit(self, cents: int) -> None: if cents <= 0: raise Refused("amount must be positive") self._balance_cents += cents def withdraw(self, cents: int, day: int) -> None: reason = self._why_not(cents, day) if reason is not None: raise Refused(reason) self._taken_today = self._taken_on(day) + cents self._day = day self._balance_cents -= cents def freeze(self) -> None: self._frozen = True def _taken_on(self, day: int) -> int: return self._taken_today if day == self._day else 0 def _why_not(self, cents: int, day: int) -> str | None: if self._frozen: return "account is frozen" if cents <= 0: return "amount must be positive" if cents > self._balance_cents: return "not enough money" if self._taken_on(day) + cents > self.DAILY_LIMIT: return "daily limit reached" return Nonedef refused(action): try: action() except Refused as why: return str(why) return Nonea = BankAccount("John", "123456")a.deposit(100_000)a.withdraw(20_000, day=1)assert refused(lambda: a.withdraw(500_000, 1)) == "not enough money"assert refused(lambda: a.withdraw(40_000, 1)) == "daily limit reached"assert a.balance_cents == 80_000 # a refusal changed nothinga.withdraw(40_000, 2)assert refused(lambda: a.deposit(-100)) == "amount must be positive"a.freeze()assert refused(lambda: a.withdraw(1, 3)) == "account is frozen"try: a.balance_cents = 1_000_000except AttributeError: print("no setter, balance is", a.balance_cents)