2.1.15 · D3OOP Fundamentals

Worked examples — Composition — has-a relationship vs is-a

2,576 words12 min readBack to topic

We first lay out a scenario matrix: a grid of every "case class" this topic throws at you. Then each worked example is tagged with the matrix cell it fills. By the end, no cell is empty.


The scenario matrix

Think of each row as a dimension the problem can vary along — like the sign of a number or the quadrant of an angle in geometry. Here the "dimensions" are the shapes a class relationship can take.

Cell Case class What makes it tricky Filled by
C1 Clean has-a part is obvious, delegate cleanly Ex 1
C2 Clean is-a true substitutability, inherit Ex 2
C3 Fake is-a (too strong) inheritance leaks a dangerous interface Ex 3
C4 Both look true — decide grammar test is ambiguous, use Liskov Ex 4
C5 Zero / empty part (degenerate) part missing or is a do-nothing object Ex 5
C6 Many parts (combinatorial) avoid class explosion Ex 6
C7 Runtime swap (limiting behaviour) change the part while running Ex 7
C8 Word problem (real world) translate English → design Ex 8
C9 Exam twist — "is-a that should be has-a" recognise the trap under time pressure Ex 9

Let me define the one measuring tool we lean on throughout, so no term is used before it's earned.

Figure — Composition — has-a relationship vs is-a

The figure above is our map: the left shape is is-a (one arrow flowing up — the child stands in for the parent), the red shape on the right is has-a (a box holding a smaller box it talks to). Every example lands on one side or the other.


Worked examples

Ex 1 — Clean has-a (cell C1)


Ex 2 — Clean is-a (cell C2)


Ex 3 — Fake is-a, too strong (cell C3)


Ex 4 — Both look true, decide with Liskov (cell C4)


Ex 5 — Zero / degenerate part (cell C5)


Ex 6 — Combinatorial explosion (cell C6)


Ex 7 — Runtime swap (limiting behaviour) (cell C7)


Ex 8 — Word problem (real world) (cell C8)


Ex 9 — Exam twist (cell C9)


Recall Which cell was which?

C1 clean has-a (Car/Engine) ::: Ex 1 C2 clean is-a (Circle/Shape) ::: Ex 2 C3 fake is-a too strong (Stack/list) ::: Ex 3 C4 both look true → Liskov decides (Queue/Deque) ::: Ex 4 C5 zero/degenerate part (Null Object engine) ::: Ex 5 C6 combinatorial explosion (Robots) ::: Ex 6 C7 runtime swap (petrol → electric) ::: Ex 7 C8 real-world word problem (coffee Order) ::: Ex 8 C9 exam twist (PremiumUser/dict) ::: Ex 9


Connections

  • 2.1.15 Composition — has-a relationship vs is-a (Hinglish)
  • Inheritance — is-a relationship
  • Liskov Substitution Principle
  • Encapsulation and Information Hiding
  • Dependency Injection
  • Strategy Pattern
  • Aggregation vs Composition (UML)
  • Fragile Base Class Problem