Notes
The problem
A delivery rider varies in two ways. How they travel: bicycle, electric scooter or motorbike. And how payment is handled: cash at the door or prepaid. With inheritance, each combination becomes a subclass, so three times two gives six classes, like bike cash rider. Add cars and you need two more. Add U P I at the door and you need four more. The travel code is copied across every payment variant.
- vehicle: bicycle, e-scooter,
- motorbike
- payment: cash, prepaid
- 3 x 2 = 6 subclasses:
- BikeCashRider
- BikePrepaidRider
- ScooterCashRider ...
- add "car": 2 more classes
- add "UPI at door": 4 more
Stuck at birth
There is a second limit. A Java object can never change its class. Arun starts the shift as a bike cash rider. His bicycle breaks, and he switches to an electric scooter. The object cannot become a scooter cash rider. You would have to create a new rider object and copy over his orders in hand and his rating, and hope nothing else still points to the old one.
Rider r = new BikeCashRider("Arun");
// bike breaks down mid-shift
// Arun takes an e-scooter
// r cannot become a
// ScooterCashRider object.
// create a new rider? lose state
// like orders in hand and rating The idea
Composition means building an object from parts that it holds, and letting each part do its own job. Inheritance says is a. Composition says has a. A delivery rider has a vehicle and has a way to collect payment. Each kind of variation becomes its own small interface, and the rider just holds one of each. The two kinds of variation stop multiplying and start adding.
- composition: build an object
- from parts it holds, and let
- each part do its own job
- inheritance: is-a
- composition: has-a
- a rider HAS a vehicle
- a rider HAS a way to collect
The structure
Here is the structure. Vehicle is an interface with one method, minutes for a distance. Bicycle and electric scooter implement it. Payment collector is another interface, with cash on delivery and prepaid behind it. With inheritance, the counts multiplied. With composition, they add: three vehicles plus two collectors. Adding a car is one class, and adding U P I at the door is one class.
- inheritance:
- vehicles x payments
- 3 x 2 = 6, growing fast
- composition:
- vehicles + payments
- 3 + 2 = 5, growing slowly
- add a car: one class
- add UPI at door: one class
Delegation
The rider holds its parts in private fields, passed in through the constructor. When asked for an arrival time, it simply asks its vehicle. When delivering an order, it asks its collector to handle payment. Passing a job to another object like this is called delegation. The rider keeps its own state, like its name and the orders in hand, and does not need to know how any part works inside.
private Vehicle vehicle;
private final PaymentCollector collector;
int etaMinutes(int km) {
return vehicle.minutesFor(km);
}
String deliver(Order o) {
return collector.collect(o);
} Run-through
Follow the demo. The dispatcher asks Arun for an arrival time for three kilometres. Arun asks his bicycle, which says twelve minutes at four minutes per kilometre. Then the dispatcher asks him to deliver order fifty one. Arun hands that to his cash on delivery collector, which records two hundred and forty rupees taken at the door. Each object answered only for its own job.
Swap at runtime
Now the bicycle breaks. The dispatcher calls switch vehicle and hands Arun an electric scooter. It is the same rider object, with the same orders in hand and the same rating. Only one part changed. The next arrival time comes from the scooter: six minutes for three kilometres. With inheritance this needed a new object. With composition it is one field assignment.
Testing
Testing becomes easy. Because Vehicle and payment collector are small interfaces with one method each, a test can pass in lambdas: a vehicle that always takes zero minutes and a collector that always says okay. Now you can test the rider's own logic, like how it tracks orders, with nothing else involved. With six subclasses, you would have had to test each combination separately.
Vehicle instant = km -> 0;
PaymentCollector noop = o -> "ok";
var r = new DeliveryRider("t",
instant, noop);
assert r.etaMinutes(5) == 0;
Vehicle is a functional interface,
so a lambda is enough No fragile base
Composition also escapes the fragile base class problem from lesson four. A subclass depends on its parent's insides, such as which methods call which. The rider depends only on the public methods of Vehicle and payment collector. The scooter team can change how they calculate time in any way they like, and as long as the contract holds, the rider is never affected.
- inheritance couples you to
- the parent's insides:
- call order, protected parts
- composition couples you
- only to public methods
- a part can change how it
- works inside and the rider
- never notices
Side by side
Side by side. Inheritance models is a, is fixed when the code is compiled, couples to the parent's insides, and makes combinations multiply. Composition models has a, can be changed at runtime, couples only to public methods, and makes combinations add. The price of composition is a little more code: you write forwarding methods instead of getting inherited ones for free.
- inherit compose
- relation is-a has-a
- fixed when compile runtime
- can swap no yes
- coupling insides public
- combinations multiply add
- code to write less a bit
- more
When to inherit
The advice says prefer, not always. Inheritance is fine for a strict is a relationship that will not change, when the base class was designed for extension with clear hooks, and when there is only one kind of variation. Some frameworks also expect you to extend their classes. The danger signs are two or more kinds of variation, and a need to change behaviour while the program is running.
- • the is-a is strict and
- will not change
- • the base was designed for
- extension (template steps)
- • one kind of variation,
- not two or more
- • framework asks for it
- (extend a test base class)
In the JDK
The Java library uses composition everywhere. A Thread is given a Runnable to run instead of being subclassed. A buffered reader wraps another reader and adds buffering on top. Collections dot synchronized list wraps any list and puts a lock around each call. A tree map takes a Comparator that decides its ordering. In each case behaviour is plugged in, not inherited.
- new Thread(runnable)
- thread has a task
- BufferedReader(Reader)
- wraps another reader
- Collections.synchronizedList
- wraps a list, adds a lock
- TreeMap(Comparator)
- has an ordering
Patterns built on it
Many design patterns are composition with a name. The vehicle and payment collector are Strategy: an algorithm held in a field and swapped when needed. Decorator wraps an object to add behaviour, like the buffered reader. State swaps the held object as the state changes. Adapter wraps an object to make it fit another interface. You will meet each of these in the patterns unit.
- Strategy: swap an algorithm
- (Vehicle, PaymentCollector)
- Decorator: wrap to add
- behaviour (BufferedReader)
- State: swap behaviour as
- the state changes
- Adapter: wrap to translate
- one interface into another
In interviews
In design rounds, reach for composition when you see variations multiplying or behaviour that changes at runtime. A parking lot holds a pricing policy. An elevator holds a scheduling strategy. A vending machine holds its current state. A logger holds sinks and formatters. The classic mistake is a tall tree like vehicle, car, electric car, electric S U V, growing one level for every new feature.
- parking lot: PricingPolicy
- held by the lot
- elevator: scheduling strategy
- vending machine: current state
- logger: sinks and formatters
- mistake: Vehicle -> Car ->
- ElectricCar -> ElectricSUV
- for every new feature