AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Verify

Attack your own class with the moves a caller could make.

The point: a test of encapsulation is an attack. Try to break each rule from outside, and look at the object after each refusal.

A trace by hand

CallSalaryRaisesResult
Employee('Alice', 7_500_000, ...)7,500,0000created
give_raise(10)8,250,00017,500,000 x 110 / 100
give_raise(60)8,250,0001ValueError, nothing changed
e.skills.append('x')8,250,0001AttributeError, tuple
keep s = e.skills, then add_skill('go')8,250,0001s is unchanged

The attack as a test

Python
from dataclasses import dataclass, FrozenInstanceError@dataclass(frozen=True)class Raise:    percent: int    before: int    after: intclass Employee:    def __init__(self, cents):        self._cents, self._raises = cents, []    @property    def cents(self): return self._cents    @property    def raises(self): return tuple(self._raises)    def give_raise(self, p):        if not 0 <= p <= 50: raise ValueError("0 to 50")        after = self._cents * (100 + p) // 100        self._raises.append(Raise(p, self._cents, after))        self._cents = afterdef refuses(action, *errors):    try: action()    except errors: return True    return Falsee = Employee(7_500_000)e.give_raise(10)before = (e.cents, e.raises)assert refuses(lambda: e.give_raise(60), ValueError)assert refuses(lambda: setattr(e, "cents", 1), AttributeError)assert refuses(lambda: e.raises.append(1), AttributeError)assert refuses(lambda: setattr(e.raises[0], "after", 1), FrozenInstanceError)assert (e.cents, e.raises) == before          # nothing movedprint("5 attacks, 0 changes:", e.cents)
The last assert is the important one. A refusal that already wrote half of the change is also a break.
Edit and run it in your browser