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
Testing the promise
Turn is a into a check: preconditions, results, invariants and history.
The point: an IS-A claim is a claim about behaviour. Write the parent's tests once, and run them on every child.
Four rules
What a subtype must keep
| Rule | Broken by | Seen as |
|---|---|---|
| Do not demand more | A child that refuses negative numbers the parent accepts | Errors in old callers |
| Do not promise less | find returns None where the parent never did | Null errors far away |
| Keep invariants | Properties accepts values that are not text | Fails later, on saving |
| No changes the parent forbids | A mutable child of an immutable type | Keys in a map that get lost |
Python
class ListStack(list): # IS-A list def push(self, x): self.append(x)s = ListStack(); s.push(1); s.push(2); s.push(3)s.insert(0, 99); s.reverse() # allowed, and no stack any moreprint("is-a:", s.pop()) # 99class Stack: # HAS-A list def __init__(self): self._items = [] def push(self, x): self._items.append(x) def pop(self): return self._items.pop() def __len__(self): return len(self._items)t = Stack(); t.push(1); t.push(2); t.push(3)print("has-a:", t.pop(), hasattr(t, "insert")) # 3 FalsePython
class Rect: def __init__(self, w, h): self.w, self.h = w, h def set_width(self, w): self.w = w def area(self): return self.w * self.hclass Square(Rect): def __init__(self, s): super().__init__(s, s) def set_width(self, w): self.w = self.h = wdef rect_contract(r): h = r.h r.set_width(7) assert r.h == h, "setting the width must not change the height" assert r.area() == 7 * hfor make in (lambda: Rect(2, 3), lambda: Square(3)): r = make() try: rect_contract(r); print(type(r).__name__, "is a Rect") except AssertionError as e: print(type(r).__name__, "is not a Rect:", e)Square fails the contract. What now?
BreaksSpecial case in the caller
- How
if isinstance(r, Square).- Limit
- Every caller, for every false subtype.
- Choose when
- Never.
WorksRemove the setters
- How
- Immutable shapes:
with_width(7)of a square returns a Rect. - Limit
- Callers must use the returned object.
- Choose when
- You own the types.
StrongShare only what is true
- How
- Both implement
Shape.area(). Neither extends the other. - Limit
- Shared code needs a helper.
- Choose when
- Nobody needs a square where a resizable rectangle is expected.
From a claim to a test