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
Public is forever
How to keep an interface small, and how to change a member that strangers already use.
The point: every public member is a promise. Make few, and when one must change, move callers in steps and keep both shapes alive for a while.
What counts as public
| Looks private | Is public because |
|---|---|
| the order of a list you return | callers start to rely on it |
| the text of an error message | somebody parses it |
| protected fields | subclasses in other code bases use them |
| serialized field names | stored files and other services read them |
| how long a call takes | a caller sets a timeout just above it |
From a field to a property, without breaking a caller
In Python and C# an attribute and a property look the same to the caller, so a public attribute can become a checked property later. In Java a field access and a method call are different code, so a public field can never grow a check without a break. That is why Java code has getters from the first day, and Python code does not need them.
class SensorV1: def __init__(self): self.celsius = 20.0class SensorV2: def __init__(self): self._milli_kelvin = 293_150 # new storage @property def celsius(self): return self._milli_kelvin / 1000 - 273.15 @celsius.setter def celsius(self, value): if value < -273.15: raise ValueError("below absolute zero") self._milli_kelvin = round((value + 273.15) * 1000)for s in (SensorV1(), SensorV2()): s.celsius = 25.0 # the caller did not change print(round(s.celsius, 2))Moving 200 callers off setBalance
- 1
Add the better way
depositandwithdrawappear next tosetBalance. Nothing breaks. - 2
Route the bad way through it
setBalance(x)computes the difference and callsdepositorwithdraw. Now the rules run for everybody. Refusals may appear: count them before you enforce. - 3
Mark and count
Mark it deprecated. Log each caller once per process, so you have a list and not a guess.
- 4
Move callers
Small commits, one team at a time. A script for the simple pattern, people for the rest.
- 5
Forbid new ones
A lint rule with a list of known callers. The list may only get shorter.
- 6
Remove
When the log has been silent for a full business cycle, for example a quarter end, delete it.
Alternatives and their price
| Way | Good | Price |
|---|---|---|
| Big change in one commit | no double life | only inside one repository with good tests |
| New class beside the old one | clean start | two truths until the last caller moved |
| Adapter with the old interface | callers untouched for now | the adapter tends to stay for years |
| Deprecate and wait | no work today | nobody moves without a date |