AlgoViz

IS-A and HAS-A

easy 40 min

IS-A says that an object is a kind of something and can stand in for it.

Watch lesson4:45

From is to has, in use

Change extends into a field without breaking callers.

The point: keep the old type alive as an interface, move the code into a part, and let both exist for a while.

Plan

Six small steps, each can be released

  1. 1

    Pin behaviour

    Tests through the old class, for what callers really use.

  2. 2

    Extract the interface

    Only the methods that callers call. Search decides, not taste.

  3. 3

    Let callers ask for the interface

    Parameter types change, objects do not.

  4. 4

    Add the field

    The class holds the former parent as a part and forwards. It still extends, for now.

  5. 5

    Cut the extends

    The compiler shows who used inherited methods that are not in the interface.

  6. 6

    Clean up

    Remove forwards that nobody calls.

Python
class Table:                                  # the former parent    def __init__(self): self.rows = {}    def put(self, k, v): self.rows[k] = v    def get(self, k): return self.rows.get(k)class OldSettings(Table):                     # is a table    def set(self, k, v):        if not isinstance(v, str): raise TypeError("text only")        self.put(k, v)class Settings:                               # has a table    def __init__(self): self._table = Table()    def set(self, k, v):        if not isinstance(v, str): raise TypeError("text only")        self._table.put(k, v)    def get(self, k): return self._table.get(k)def test(s):    s.set("lang", "en")    assert s.get("lang") == "en"for cls in (OldSettings, Settings):    test(cls())old = OldSettings(); old.put("size", 12)      # past the rule, through the parentprint("old holds", old.get("size"), "| new has put:", hasattr(Settings(), "put"))
Before and after under one test. The wrapper keeps the old calls and drops the dangerous ones.
Edit and run it in your browser

What usually gets in the way

ProblemAnswer
isinstance(x, Table) in callersReplace by the interface or by a method
Protected fields used in childrenMake them private to the part, add a method
The parent calls its own overridable methodsThe part must get a callback, or the step stays inside the part
Stored or serialised class namesFixed tags before the move
EqualityDecide whether wrapper and part may be equal. Usually not

Where to stop