Composition over inheritance: end the subclass explosion
Build each rental from parts, so a new car is one small class.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–9Payoff
Steps 10–11Recap
Steps 12–13The code: before and after
Before
class Rental
def initialize(days)
@days = days
end
def price
raise NotImplementedError, "#{self.class}#price"
end
end
class EconomyRental < Rental
def price
30 * @days
end
end
class SuvRental < Rental
def price
50 * @days + 20
end
end
class InsuredEconomy < EconomyRental
def price
super + 15 * @days
end
end
class InsuredSuv < SuvRental
def price
super + 15 * @days
end
end
def desk
city = EconomyRental.new(3)
trip = InsuredSuv.new(3)
puts "#{city.price} #{trip.price}" # 90 215
end
deskAfter
class EconomyCar
def price(days)
30 * days
end
end
class SuvCar
def price(days)
50 * days + 20
end
end
class VanCar
def price(days)
70 * days
end
end
class Insurance
def price(days)
15 * days
end
end
class NoCover
def price(days)
0
end
end
class Rental
def initialize(car, cover, days)
@car = car
@cover = cover
@days = days
end
def price
@car.price(@days) + @cover.price(@days)
end
end
def desk
city = Rental.new(EconomyCar.new, NoCover.new, 3)
trip = Rental.new(SuvCar.new, Insurance.new, 3)
move = Rental.new(VanCar.new, Insurance.new, 3)
puts "#{city.price} #{trip.price} #{move.price}" # 90 215 255
end
deskTranscript, step by step
Problem
Step 1: A car rental desk Before
At the car rental desk from the last lesson, a rental knows its days, and each subclass sets the price. Economy Rental and SUV Rental each price one car kind, and insurance adds fifteen dollars a day on top of super. Insurance came after the car classes, so extending each one added it without touching them, their callers, or an if inside every price. The desk rents an economy car and an insured SUV for three days, and prints ninety and two hundred fifteen.
Step 2: Vans join the fleet Code smell
The fleet now has vans, at seventy dollars a day, and customers can insure them too. The quick way adds Van Rental, and then Insured Van, which extends it and adds the same fifteen dollars a day. The desk rents an insured van for three days, and the run prints two hundred fifty five as the third price.
Step 3: A subclass for every pair Code smell
This is a subclass explosion, when a class varies in two independent ways and inheritance needs one subclass for every pair. Here the two ways are the car kind and the cover, so every car kind needs a second class for insurance. You can see the insurance rule here, here, and here. A subclass per kind worked last lesson, because rentals varied in only one way, the car, but a second way multiplies the classes. One van needed two classes, and the insurance rule now lives in three places, so changing the insurance price means three edits.
Refactor
Step 4: Refactor first Back it out
With vans, three car kinds times two choices of cover make six rental classes, and a premium cover would make it nine. So let's take the vans out again. We'll refactor first, so car and cover become separate parts, and then vans will need one new class.
Step 5: Insurance gets a class Extract Class
First, the insurance rule moves into a class of its own, Insurance, with a price for a number of days. Both insured subclasses now ask a new Insurance for its price, instead of adding fifteen a day themselves. The rule lives in one place now, and the run still prints ninety and two hundred fifteen.
Step 6: A cover for no cover Introduce Null Object
A rental without insurance will still need a cover, so No Cover has the same price method and returns zero. This is a Null Object, an object that stands in for nothing, so an uninsured rental will need no nil check and no if. Ruby has no interface keyword, so a cover is any object that responds to price with a number of days, and both classes do. That duck typing matters next, because the rental will soon hold a cover of any kind.
Step 7: The rental holds a cover Replace Subclass with Delegate
Now Rental gets a cover, passed in through initialize and kept in an instance variable. Its price is concrete now, the car's price plus the cover's price for the same days. This is composition, where the rental holds a cover as a field and asks it for its part of the price. The cover is the rental's delegate, the object it hands that part of the work to. Economy Rental and SUV Rental override car price instead, both insured subclasses are deleted, and the desk passes each rental its cover.
Step 8: Each car gets a class Extract Class
The car kind gets the same treatment, so each car's price moves into its own class, Economy Car and SUV Car. Economy Rental and SUV Rental now ask a new car object for the price inside car price. Both car classes respond to price with a number of days, the same duck type that Insurance and No Cover share.
Step 9: The rental holds a car Replace Subclass with Delegate
Last, Rental holds a car as well, and its price adds the car's price and the cover's price. Nothing extends Rental anymore, so the Not Implemented Error goes too, and the car is its second delegate. Economy Rental, SUV Rental and car price are deleted, and the desk builds each rental from a car, a cover and the days. The run still prints ninety and two hundred fifteen, so nothing changed for the desk's customers.
Payoff
Step 10: Vans, as one class Add vans
Now vans come back, and this time they are one new class, Van Car, at seventy dollars a day. The desk rents a van with Insurance for three days, and the run prints two hundred fifty five. Rental, the other two cars and both covers didn't change, and no insured van class exists.
Step 11: Parts add up Composition over inheritance
The three copies of the insurance rule are now one, here in Insurance. A premium cover would be one more class with a price method, and every car kind could use it. The Gang of Four put it as favor object composition over class inheritance, and it fits here because rentals vary in two independent ways. As fields, each way grows on its own, so three cars plus two covers make five small classes, where inheritance needed six rental subclasses.
Recap
Step 12: Where we started, where we ended Before / after
On the left, every pair of car kind and cover had its own subclass, with the insurance rule copied into each insured one. On the right, Rental holds a car and a cover, and adds their two prices. Each car kind, like SUV Car, and each cover, like Insurance, is one small class of its own.
Step 13: When to reach for it Takeaways
Reach for it when a class varies in two or more independent ways, like car kind and cover. Skip it when there's only one way to vary, like last lesson's rentals, because nothing multiplies and a delegate only adds an object and a call. You'll spot the need by class names that join words from two lists, like Insured SUV, and the same override copied across sibling subclasses. Ruby's Logger writes to any IO object it holds, so there's no separate logger subclass for files and for the console.