Skip to the guide

Composition over inheritance

IntermediateConcept6 pages

Composition means a class gets a behaviour by holding another object that has it, and asking that object to do the work. Inheritance means the class gets the behaviour by extending a parent class. When a behaviour varies, interviewers want to hear which of the two you pick, and what the other choice would cost in classes and in changes.

A drill and its bits

Think of a cordless drill. At the front it has a chuck, the grip that holds any bit, and underneath it has a slot that takes any battery of its brand. You buy one drill, a few bits and two batteries. Halfway through a job you swap the wood bit for a masonry bit, and the same drill stays in your hand. Nobody sells a separate drill for every pair of bit and battery, because the shop would need a new shelf of drills for every new bit.

In code, the drill is the Courier class from this page's project, a delivery courier who rides a bicycle, a scooter or a van, and who is paid per delivery or by the hour. The chuck is the Vehicle interface, and the bits are the classes behind it: Bicycle, Scooter and Van. The battery slot is the PayRule interface, with PerDelivery and Hourly as the batteries. Swapping the bit in the middle of a job is switchTo. The shelf with a drill for every pair is a subclass for every combination of vehicle and pay.