Ensuring proper encapsulation
medium 40 minPrivate fields are the start, not the end.
Watch lesson4:46
Closing a leak safely
The getter is public and 60 places use it. How do you close it?
The point: find out who writes through the leak, give them an action, and only then close it. Closing first breaks callers at run time.
Five moves
- 1
Count the users
Search for
.members()and look what follows:append,sort,clear, an assignment into an element. Readers and writers are different problems. - 2
Watch in production
Return a list that logs writes with a stack trace. It behaves the same, so nothing breaks, and you learn about callers that search cannot see.
- 3
Add the action
For each kind of write make a method:
add_member,remove_member. Move the callers in small commits. - 4
Return a snapshot
First in tests, then for a part of the traffic. A caller that still writes now fails loudly or writes into a copy. Prefer loud: a tuple, an unmodifiable list.
- 5
Add a guard
A test that changes what it got and compares the object. A lint rule for new leaks, such as the SpotBugs patterns EI_EXPOSE_REP and EI_EXPOSE_REP2.
The logging list
import tracebackclass WatchedList(list): """Behaves like a list, reports who writes. A tool for a few weeks, not a design.""" def __init__(self, items, report): super().__init__(items) self._report = reportdef _watch(name): def method(self, *a, **k): caller = traceback.extract_stack(limit=2)[0] self._report(f"{name} from {caller.name}") return getattr(list, name)(self, *a, **k) return methodfor n in ("append", "extend", "insert", "remove", "pop", "clear", "sort", "reverse", "__setitem__", "__delitem__"): setattr(WatchedList, n, _watch(n))seen = []members = WatchedList(["lee", "asha"], seen.append)def show_page(): members.sort() # the writer nobody expecteddef count_page(): return len(members)show_page(); count_page()print(seen, members)Failure walk
| Minute | What happens | What helps |
|---|---|---|
| 0 | Release: skills() now returns an unmodifiable list | flag per service, 5% of traffic |
| 3 | Export job fails with UnsupportedOperationException: it sorted the list | error names the class and the caller |
| 5 | Flag off. A loud failure, and no data was harmed | the old way still exists behind the flag |
| 30 | Export sorts its own copy. A search finds two more | the watching list had a blind spot: monthly jobs |
| next month | Flag on for all, flag removed | keep the attack test |
What not to do
Silently returning a copy to old writers is the worst of the options. Their code still runs, and their changes disappear. A loud failure is kinder.