Ensuring proper encapsulation
medium 40 minPrivate fields are the start, not the end.
Watch lesson4:46
Side doors
Seven ways around a perfect set of methods.
The point: look for every path on which a reference or a half built object can leave. Methods are only one of them.
The inspection list
| Door | How it opens | How to close it |
|---|---|---|
| Subclass | protected fields, overridden methods that skip the check | final class, private fields, small hooks. See Preventing subclassing |
this escapes | constructor registers itself as a listener before it is finished | static factory: build, then register |
| Overridable call in the constructor | subclass method runs before its fields exist | call only private or final methods there |
| Callback | a listener calls back while the state is half written | finish all writes, then notify from a copy of the listener list |
| Iterator or lambda | an inner iterator with remove, a closure over a field | iterate over a snapshot |
| Serialization, JSON, ORM | fields are set by reflection, no constructor runs | map to a DTO and go through the constructor |
| Text output | toString prints a token, an error contains the balance | print an id, mask the rest |
| Static field | static List CACHE is shared by all instances | private, immutable, or an injected object |
The callback that came too early
Python
class Early: def __init__(self): self._total, self._lines, self._listeners = 0, [], [] def on_change(self, f): self._listeners.append(f) def add(self, cents): self._lines.append(cents) for f in self._listeners: f(self) # rule is false right now self._total += centsclass Late(Early): def add(self, cents): self._lines.append(cents) self._total += cents for f in list(self._listeners): f(self) # rule holds, and the list may changedef rule(c): print(type(c).__name__, "rule holds:", c._total == sum(c._lines))for cls in (Early, Late): c = cls() c.on_change(rule) c.add(500)The half built object
A reference leaves before the end
What about reflection?
In most languages a determined caller can get in: reflection in Java, _Class__name in Python, a cast in C++. Encapsulation protects against mistakes and keeps the cost of change low. It is not a security border between programs. For untrusted code use a process or a sandbox. Java modules are the strong exception inside one process: since Java 17 deep reflection into JDK internals is refused by default.