IS-A and HAS-A
easy 40 minIS-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
Pin behaviour
Tests through the old class, for what callers really use.
- 2
Extract the interface
Only the methods that callers call. Search decides, not taste.
- 3
Let callers ask for the interface
Parameter types change, objects do not.
- 4
Add the field
The class holds the former parent as a part and forwards. It still extends, for now.
- 5
Cut the extends
The compiler shows who used inherited methods that are not in the interface.
- 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"))What usually gets in the way
| Problem | Answer |
|---|---|
isinstance(x, Table) in callers | Replace by the interface or by a method |
| Protected fields used in children | Make them private to the part, add a method |
| The parent calls its own overridable methods | The part must get a callback, or the step stays inside the part |
| Stored or serialised class names | Fixed tags before the move |
| Equality | Decide whether wrapper and part may be equal. Usually not |
Where to stop