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

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

RuleBroken bySeen as
Do not demand moreA child that refuses negative numbers the parent acceptsErrors in old callers
Do not promise lessfind returns None where the parent never didNull errors far away
Keep invariantsProperties accepts values that are not textFails later, on saving
No changes the parent forbidsA mutable child of an immutable typeKeys in a map that get lost
Language checks cover signatures only. The rest needs tests. More on Liskov substitution.
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 False
A stack that is a list inherits 40 ways to break a stack. A stack that has a list offers three.
Edit and run it in your browser
Python
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)
A contract test that finds the false subtype. Every new child is one more entry.
Edit and run it in your browser

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