0
Challenge · 79CS Fundamentals
Inheritance vs composition
OOPused in ~90% of apps
Inheritance is the feature every OOP tutorial teaches first and every experienced codebase uses least. The advice you will hear quoted is favour composition over inheritance, and the interview question is not whether you have heard it but whether you can say why.
Core idea. Inheritance says a type IS a kind of another type and inherits everything about it, permanently. Composition says an object HAS some behaviours, chosen at the time and changeable. Inheritance handles one axis of variation and multiplies badly across two.
poke it, drag it,
try to break it
try to break it
no slides here.
you drive.
you drive.
Playground, this isn't a screenshot
tick the behaviours an item needs
with inheritance
class PlainItem
One class per combination. Three behaviours need 8 classes, and a fourth needs 16.
with composition
traits: []
One item, a list of behaviours. Three behaviours need 3 functions, and a fourth needs 4.
Inheritance grows as two to the number of behaviours. Composition grows as the number of behaviours.
↑ play a little first, then dig in