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
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.
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"]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?
| Question | Decoration | Real |
|---|---|---|
| How many public methods are plain getters and setters? | nearly all | few |
| How many files change when a field changes type? | many | one |
| Where are the rules about the data? | in services | in the class |
| Can tests run against a second implementation? | no | yes |
| Does a caller need a fixed order of calls? | yes, in a comment | no, or the type enforces it |
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