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

Keep it sealed

A check that fails the build, what to measure, and how to tell real hiding from decoration.

The point: a convention holds for a week. A check in the build holds for years. Measure whether the hiding pays, too.

A small guard for Python

Python has no lock, so we write one for the build. It reads the code as a tree and reports every x._name where x is not self or cls.

Python
import astdef outside_access(source: str) -> list[str]:    found = []    for node in ast.walk(ast.parse(source)):        if not isinstance(node, ast.Attribute):            continue        name = node.attr        private = name.startswith("_") and not name.startswith("__")        own = isinstance(node.value, ast.Name) and node.value.id in ("self", "cls")        if private and not own:            found.append((node.lineno, name))    return [f"line {line}: {name}" for line, name in sorted(found)]code = '''class Account:    def pay(self):        self._balance -= 1          # fine, own fielddef fix(account):    account._balance = 1000         # reported    return account.balance          # fine, public'''print(outside_access(code))assert outside_access(code) == ["line 7: _balance"]
Twenty lines. Start with a list of known cases that may only shrink, so the first run does not block everybody.
Edit and run it in your browser

It misses getattr(a, '_' + name) and reports the harmless other._x inside __eq__. Allow that one by name. Existing tools do this better: Pylint has protected-access, and for Java the compiler and ArchUnit tests do the job.

Is the hiding real?

QuestionDecorationReal
How many public methods are plain getters and setters?nearly allfew
How many files change when a field changes type?manyone
Where are the rules about the data?in servicesin the class
Can tests run against a second implementation?noyes
Does a caller need a fixed order of calls?yes, in a commentno, or the type enforces it
The second line is the best single number. Take the last ten changes of a field from version control and count the files.

The cost of walls

Calls through small methods are usually inlined by the JIT or by a C++ compiler, so a getter in a hot loop is rarely the problem there. In CPython a property call is a real function call: in a loop over ten million items it matters, so read the value once before the loop. Measure before you open a field.

A pull request makes a field public