Polymorphism: One Call, Many Behaviors

When the desk checks what kind of vehicle it has before it can price it, every new vehicle means another check, and a forgotten one prices it at $0; polymorphism moves each price into its own class, so one call, rental.price(hours), does the right thing for a bike, an e-bike and a scooter.

Apprentice · OOP · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Replace a chain of checks on an object's type with one method call that each class answers its own way
  • Predict which class's method runs when the same call is made on different objects

Key takeaways

  • A chain of checks on an object's type (is it a bike? an e-bike?) has to grow with every new kind, and a forgotten check is a quiet bug.
  • Polymorphism means one call can behave differently depending on the object that answers it.
  • Move each kind's behavior into its own class, and the calling code makes one call and never asks what kind it has.
  • The variable's type decides what you may call; the object's own class decides which code runs.

Before this: Interfaces: A Promise Any Class Can Keep, whose Rentable promise this lesson uses.

Here's a bug that turns up in real apps all the time. Pedal & Go's stock team adds scooters to the fleet. The scooter class is written, the desk can rent one, and at the end of the day the report says a scooter rental cost $0. Nobody wrote a wrong price. Nobody wrote a price at all, in the one place that needed it. This lesson is about the design that makes that bug impossible, and it's called polymorphism: one call, many behaviors.

The desk that checks what it has

In this version of the desk, the vehicles only know their names. The desk knows every price, and to find one it checks what kind of vehicle it's holding:

List<Rental> rentals = new List<Rental>
{
    new Rental(new Bike(), 2),
    new Rental(new EBike(), 3),
    new Rental(new Scooter(), 2),
};
int total = 0;
foreach (Rental rental in rentals)
{
    int price = PriceOf(rental.Item, rental.Hours);
    Console.WriteLine(quot;{rental.Item.Name}, {rental.Hours} hours: ${price}");
    total += price;
}
Console.WriteLine(quot;Total: ${total}");

// The desk knows every vehicle's price, and checks which kind it has.
int PriceOf(IRentable item, int hours)
{
    if (item is Bike) { return 10 * hours; }
    if (item is EBike) { return 15 * hours; }
    return 0;
}

interface IRentable { string Name { get; } }
class Bike : IRentable { public string Name => "Bike"; }
class EBike : IRentable { public string Name => "E-bike"; }
class Scooter : IRentable { public string Name => "Scooter"; }
record Rental(IRentable Item, int Hours);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $0
Total: $65
interface Rentable { String name(); }
class Bike implements Rentable { public String name() { return "Bike"; } }
class EBike implements Rentable { public String name() { return "E-bike"; } }
class Scooter implements Rentable { public String name() { return "Scooter"; } }
record Rental(Rentable item, int hours) {}

// The desk knows every vehicle's price, and checks which kind it has.
int priceOf(Rentable item, int hours) {
    if (item instanceof Bike) { return 10 * hours; }
    if (item instanceof EBike) { return 15 * hours; }
    return 0;
}

void main() {
    List<Rental> rentals = List.of(
        new Rental(new Bike(), 2),
        new Rental(new EBike(), 3),
        new Rental(new Scooter(), 2));
    int total = 0;
    for (Rental rental : rentals) {
        int price = priceOf(rental.item(), rental.hours());
        IO.println(rental.item().name() + ", " + rental.hours() + " hours: quot; + price);
        total += price;
    }
    IO.println("Total: quot; + total);
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $0
Total: $65
class Bike:
    name = "Bike"


class EBike:
    name = "E-bike"


class Scooter:
    name = "Scooter"


def price_of(item, hours):
    """The desk knows every vehicle's price, and checks which kind it has."""
    if isinstance(item, Bike):
        return 10 * hours
    if isinstance(item, EBike):
        return 15 * hours
    return 0


rentals = [(Bike(), 2), (EBike(), 3), (Scooter(), 2)]
total = 0
for item, hours in rentals:
    price = price_of(item, hours)
    print(f"{item.name}, {hours} hours: ${price}")
    total += price
print(f"Total: ${total}")
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $0
Total: $65
class Bike { name = "Bike"; }
class EBike { name = "E-bike"; }
class Scooter { name = "Scooter"; }

// The desk knows every vehicle's price, and checks which kind it has.
function priceOf(item, hours) {
  if (item instanceof Bike) { return 10 * hours; }
  if (item instanceof EBike) { return 15 * hours; }
  return 0;
}

const rentals = [
  { item: new Bike(), hours: 2 },
  { item: new EBike(), hours: 3 },
  { item: new Scooter(), hours: 2 },
];
let total = 0;
for (const rental of rentals) {
  const price = priceOf(rental.item, rental.hours);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
  total += price;
}
console.log(`Total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $0
Total: $65
interface Rentable { name: string; }
class Bike implements Rentable { name = "Bike"; }
class EBike implements Rentable { name = "E-bike"; }
class Scooter implements Rentable { name = "Scooter"; }

interface Rental { item: Rentable; hours: number; }

// The desk knows every vehicle's price, and checks which kind it has.
function priceOf(item: Rentable, hours: number): number {
  if (item instanceof Bike) { return 10 * hours; }
  if (item instanceof EBike) { return 15 * hours; }
  return 0;
}

const rentals: Rental[] = [
  { item: new Bike(), hours: 2 },
  { item: new EBike(), hours: 3 },
  { item: new Scooter(), hours: 2 },
];
let total = 0;
for (const rental of rentals) {
  const price = priceOf(rental.item, rental.hours);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
  total += price;
}
console.log(`Total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $0
Total: $65

is in C#, instanceof in Java, JavaScript and TypeScript, and isinstance in Python all ask the same question: is this object of that class? The scooter fell through every check and landed on return 0.

The trouble isn't the missing line; it's where the knowledge lives. A scooter's price is a fact about scooters, but it's kept in the desk, so whoever adds a vehicle has to know to go and edit the desk. And the desk's chain grows with every new kind, in every place that needs a price.

Let each class answer for itself

At a sports camp, the coach blows one whistle that means "warm up!" The swimmers swim a lap, the runners jog around the track, and the cyclists spin their pedals. The coach doesn't tell each group how to warm up, or even check which group is which. The signal is the same; each group knows its own warm-up.

That's the fix: move each price into its own class, as a price(hours) method, and have the desk ask the object instead of checking what it is:

A diagram: on the left, one box "the desk" with three arrows, each labeled "price(2)", going to three boxes on the right, "Bike", "E-bike" and "Scooter"; each box sends back a reply on a dashed arrow, "$20", "$30" and "$16"

List<Rental> rentals = new List<Rental>
{
    new Rental(new Bike(), 2),
    new Rental(new EBike(), 3),
    new Rental(new Scooter(), 2),
};
int total = 0;
foreach (Rental rental in rentals)
{
    int price = rental.Item.Price(rental.Hours);
    Console.WriteLine(quot;{rental.Item.Name}, {rental.Hours} hours: ${price}");
    total += price;
}
Console.WriteLine(quot;Total: ${total}");

interface IRentable
{
    string Name { get; }
    int Price(int hours);
}

class Bike : IRentable { public string Name => "Bike"; public int Price(int hours) => 10 * hours; }
class EBike : IRentable { public string Name => "E-bike"; public int Price(int hours) => 15 * hours; }
class Scooter : IRentable { public string Name => "Scooter"; public int Price(int hours) => 8 * hours; }
record Rental(IRentable Item, int Hours);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
Total: $81
interface Rentable {
    String name();
    int price(int hours);
}

class Bike implements Rentable { public String name() { return "Bike"; } public int price(int hours) { return 10 * hours; } }
class EBike implements Rentable { public String name() { return "E-bike"; } public int price(int hours) { return 15 * hours; } }
class Scooter implements Rentable { public String name() { return "Scooter"; } public int price(int hours) { return 8 * hours; } }
record Rental(Rentable item, int hours) {}

void main() {
    List<Rental> rentals = List.of(
        new Rental(new Bike(), 2),
        new Rental(new EBike(), 3),
        new Rental(new Scooter(), 2));
    int total = 0;
    for (Rental rental : rentals) {
        int price = rental.item().price(rental.hours());
        IO.println(rental.item().name() + ", " + rental.hours() + " hours: quot; + price);
        total += price;
    }
    IO.println("Total: quot; + total);
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
Total: $81
class Bike:
    name = "Bike"

    def price(self, hours):
        return 10 * hours


class EBike:
    name = "E-bike"

    def price(self, hours):
        return 15 * hours


class Scooter:
    name = "Scooter"

    def price(self, hours):
        return 8 * hours


rentals = [(Bike(), 2), (EBike(), 3), (Scooter(), 2)]
total = 0
for item, hours in rentals:
    price = item.price(hours)
    print(f"{item.name}, {hours} hours: ${price}")
    total += price
print(f"Total: ${total}")
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
Total: $81
class Bike { name = "Bike"; price(hours) { return 10 * hours; } }
class EBike { name = "E-bike"; price(hours) { return 15 * hours; } }
class Scooter { name = "Scooter"; price(hours) { return 8 * hours; } }

const rentals = [
  { item: new Bike(), hours: 2 },
  { item: new EBike(), hours: 3 },
  { item: new Scooter(), hours: 2 },
];
let total = 0;
for (const rental of rentals) {
  const price = rental.item.price(rental.hours);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
  total += price;
}
console.log(`Total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
Total: $81
interface Rentable {
  name: string;
  price(hours: number): number;
}

class Bike implements Rentable { name = "Bike"; price(hours: number): number { return 10 * hours; } }
class EBike implements Rentable { name = "E-bike"; price(hours: number): number { return 15 * hours; } }
class Scooter implements Rentable { name = "Scooter"; price(hours: number): number { return 8 * hours; } }

interface Rental { item: Rentable; hours: number; }

const rentals: Rental[] = [
  { item: new Bike(), hours: 2 },
  { item: new EBike(), hours: 3 },
  { item: new Scooter(), hours: 2 },
];
let total = 0;
for (const rental of rentals) {
  const price = rental.item.price(rental.hours);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
  total += price;
}
console.log(`Total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
Total: $81

The desk's code has no if in it now, and no vehicle's price. It makes one call, price(hours), and each object answers its own way. In C#, Java and TypeScript, a new vehicle that forgets its price won't compile, because the promise demands one. In Python and JavaScript, any object with a price method works, promise or not: the same call still finds each object's own method.

The C# and Java versions write Rental as a record, a one-line class that only holds values. Python uses pairs, and JavaScript and TypeScript use plain objects.

How it got its name

Polymorphism is Greek for "many shapes": one call, many behaviors. It's one of the ideas object-oriented languages were built for.

How does the program know which price to run? Look at the C# line int price = rental.Item.Price(rental.Hours);. The variable Item is an IRentable; that decides what you're allowed to call (only what the promise lists). But which code runs is decided while the program runs, by the class of the object that's actually there: a Scooter's Price, if it's a scooter. That choice made at run time is called dynamic dispatch. You'll lean on it in nearly every pattern in this course: the code that makes the call stays the same, and the behavior changes with the object you hand it.

When the check is fine

Not every type check is a smell. Code that reads data from outside, such as a file or a web request, often has to check what it got before it can do anything with it. The smell is the same chain of checks in the code that uses your own classes, growing by one branch every time a new kind arrives.

Try it. Add a Tandem at $20 an hour to the second version, and rent it for 2 hours. The total becomes $121, and the loop doesn't change.

Check yourself

2 questions to try on the lesson page.

So what

Ask the object, don't check what it is: when each class answers the same call its own way, a new kind of thing is one new class, and nothing that uses it ever needs a new if.

Key terms

Cheat sheets