I'll Be Backend
Principles · Ruby

Polymorphism: subclasses instead of a type field

Let each kind answer for itself, so a new kind adds no new case.

12 steps4 chapters~4 min at 1.25×#oop#polymorphism#subclasses#type code
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Ruby video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–8

Payoff

Steps 9–10

Recap

Steps 11–12

The code: before and after

Before

class Rental
  def initialize(type, days)
    @type = type
    @days = days
  end

  def price
    case @type
    when "economy" then 30 * @days
    when "suv" then 50 * @days + 20
    else raise ArgumentError, @type
    end
  end

  def free_km
    case @type
    when "economy" then 200 * @days
    when "suv" then 150 * @days
    else raise ArgumentError, @type
    end
  end
end

def desk
  city = Rental.new("economy", 3)
  trip = Rental.new("suv", 3)
  puts "#{city.price} #{city.free_km}" # 90 600
  puts "#{trip.price} #{trip.free_km}" # 170 450
end

desk

After

class Rental
  def initialize(days)
    @days = days
  end

  def price
    raise NotImplementedError, "#{self.class}#price"
  end

  def free_km
    raise NotImplementedError, "#{self.class}#free_km"
  end
end

class EconomyRental < Rental
  def price
    30 * @days
  end

  def free_km
    200 * @days
  end
end

class SuvRental < Rental
  def price
    50 * @days + 20
  end

  def free_km
    150 * @days
  end
end

class VanRental < Rental
  def price
    70 * @days
  end

  def free_km
    100 * @days
  end
end

def desk
  city = EconomyRental.new(3)
  trip = SuvRental.new(3)
  move = VanRental.new(3)
  puts "#{city.price} #{city.free_km}" # 90 600
  puts "#{trip.price} #{trip.free_km}" # 170 450
  puts "#{move.price} #{move.free_km}" # 210 300
end

desk

Transcript, step by step

Problem

Step 1: A car rental desk Before

At a car rental desk, a rental knows its type and how many days it runs. Price and free kilometers each run a case statement on the type to find the rule for that car. The desk method rents an economy car and an SUV for three days, and prints the price and free kilometers of each.

Step 2: Vans join the fleet Code smell

The fleet now has vans, at seventy dollars a day with a hundred free kilometers a day. The quick way adds a van branch to the price case, and then another one to the free kilometers case. The desk rents a van for three days, and the run prints two hundred ten and three hundred.

Step 3: One string, a case per method Code smell

A type field, which Fowler calls a type code, is a string that says what kind of thing an object is. So every method has to run a case statement on that string before it can do its job. You can see the type field here, the case in price here, and the case in free kilometers here. Every new kind of car means opening Rental and editing every case in it, so the van's rules end up spread over every method. A deposit method would add a third case, and every later kind would edit all three.

Refactor

Step 4: Refactor first Back it out

Let's take the vans out again. We'll refactor first, so each kind of car gets its own class, and then vans will be one new class.

Step 5: One class per kind Replace Type Code with Subclasses

First, each kind of car gets a subclass, a class that extends Rental, which now plays the superclass. Economy Rental and SUV Rental have only a constructor, which passes its type string and the days up to Rental. The desk now creates the subclasses, and both case statements still work unchanged.

Step 6: Each kind sets its price Replace Conditional with Polymorphism

Next, each subclass overrides price with the line from its own branch. Ruby has no abstract keyword, so Rental's price raises Not Implemented Error, and the price case is gone. This is polymorphism, because the desk asks every rental the same question, and each subclass answers it its own way. Last lesson pulled shared code up into a superclass, and this one pushes the code that differs down into subclasses.

Step 7: Each kind sets its kilometers Replace Conditional with Polymorphism

Free kilometers gets the same move, and each subclass overrides it with the line from its own branch. Rental's free kilometers raises the same error now, so the second case is gone as well.

Step 8: The type string goes Remove Dead Code

Nothing reads the type field anymore, because no case statement is left to ask it. So the field and its constructor parameter are deleted, and the subclass constructors go too, because each one only passed a string up.

Payoff

Step 9: Vans, as one class Add vans

Now vans come back, and this time they are one new class, Van Rental. It overrides price with seventy dollars a day, and free kilometers with a hundred a day. Rental, Economy Rental and SUV Rental didn't change, and the desk only gains the two van lines.

Step 10: Each kind answers for itself Payoff

The type field used to sit here, and the two case statements used to sit here and here. All the van's rules sit in one class now, so the next kind of car is one new class too. This is the Open Closed Principle, because Rental is open for extension and closed for change. It fits here because the fleet grows by kinds of car, while the questions the desk asks, price and free kilometers, stay the same. And if a new class leaves out free kilometers, Ruby raises Not Implemented Error only when someone calls it, not when the class loads.

Recap

Step 11: Where we started, where we ended Before / after

On the left, Rental keeps a type string, and price and free kilometers each run a case on it. On the right, Rental holds only the days and leaves the two questions to its subclasses. Each kind of car, like Economy Rental, answers both questions in its own class.

Step 12: When to reach for it Takeaways

Reach for it when two or more methods run a case on the same type field. Skip it when an object changes kind while it lives, like a rental upgraded mid-trip, because an object keeps the class it was created with, so use State or Strategy instead. You'll spot the need by the same case or if chain on one field, repeated in several methods.