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

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 privateIs public because
the order of a list you returncallers start to rely on it
the text of an error messagesomebody parses it
protected fieldssubclasses in other code bases use them
serialized field namesstored files and other services read them
how long a call takesa 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.

Python
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))
The same two lines of caller code work with the field and with the property.
Edit and run it in your browser

Moving 200 callers off setBalance

  1. 1

    Add the better way

    deposit and withdraw appear next to setBalance. Nothing breaks.

  2. 2

    Route the bad way through it

    setBalance(x) computes the difference and calls deposit or withdraw. Now the rules run for everybody. Refusals may appear: count them before you enforce.

  3. 3

    Mark and count

    Mark it deprecated. Log each caller once per process, so you have a list and not a guess.

  4. 4

    Move callers

    Small commits, one team at a time. A script for the simple pattern, people for the rest.

  5. 5

    Forbid new ones

    A lint rule with a list of known callers. The list may only get shorter.

  6. 6

    Remove

    When the log has been silent for a full business cycle, for example a quarter end, delete it.

Alternatives and their price

WayGoodPrice
Big change in one commitno double lifeonly inside one repository with good tests
New class beside the old oneclean starttwo truths until the last caller moved
Adapter with the old interfacecallers untouched for nowthe adapter tends to stay for years
Deprecate and waitno work todaynobody moves without a date