Prefer Composition to Inheritance

When every combination of options becomes its own subclass, the classes multiply until a burrito with extra cheese and no onion needs a class of its own; building an item from parts it holds (composition) instead of from a family tree of subclasses (inheritance) turns each new option into one new part.

Apprentice · OOP · Software Development · Updated

By

After this lesson you can

  • Build an object from parts it holds (has-a) instead of writing a subclass for every combination
  • Choose between inheritance and composition for a design, and say why

Key takeaways

  • A subclass for every combination of options multiplies: each new option doubles the number of classes. That's called a class explosion.
  • Inheritance is decided when you write the class. Composition is decided when you build the object, so it can mix parts freely.
  • Build from parts: a menu item has a list of extras, and each extra is a small object with a name and a price.
  • Prefer composition, but don't ban inheritance: a true is-a with nothing to combine is still a good use of it.

Before this: Inheritance and Composition: Is-a and Has-a.

Customers at the food truck's window started asking for changes to their order: extra cheese, no onion. The developer reached for inheritance, which is the first tool most of us learn: a burrito with extra cheese is a burrito, so it's a subclass. A month later there are more classes than menu items, and guacamole is next. This lesson shows why, and ends with the third idea behind the patterns: prefer composition to inheritance.

The symptom: a class for every combination

Here are the burrito's classes so far. Extra cheese is $1, and no onion costs nothing:

List<Burrito> orders = new List<Burrito> { new Burrito(), new BurritoExtraCheese(), new BurritoNoOnion(), new BurritoExtraCheeseNoOnion() };
foreach (Burrito order in orders)
{
    Console.WriteLine(quot;{order.Name()}: ${order.Price()}");
}

class Burrito
{
    public virtual string Name() => "burrito";
    public virtual int Price() => 9;
}

class BurritoExtraCheese : Burrito
{
    public override string Name() => "burrito, extra cheese";
    public override int Price() => 10;
}

class BurritoNoOnion : Burrito
{
    public override string Name() => "burrito, no onion";
}

class BurritoExtraCheeseNoOnion : BurritoExtraCheese
{
    public override string Name() => "burrito, extra cheese, no onion";
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
class Burrito {
    String name() { return "burrito"; }
    int price() { return 9; }
}

class BurritoExtraCheese extends Burrito {
    String name() { return "burrito, extra cheese"; }
    int price() { return 10; }
}

class BurritoNoOnion extends Burrito {
    String name() { return "burrito, no onion"; }
}

class BurritoExtraCheeseNoOnion extends BurritoExtraCheese {
    String name() { return "burrito, extra cheese, no onion"; }
}

void main() {
    List<Burrito> orders = List.of(new Burrito(), new BurritoExtraCheese(), new BurritoNoOnion(), new BurritoExtraCheeseNoOnion());
    for (Burrito order : orders) {
        IO.println(order.name() + ": quot; + order.price());
    }
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
class Burrito:
    def name(self):
        return "burrito"

    def price(self):
        return 9


class BurritoExtraCheese(Burrito):
    def name(self):
        return "burrito, extra cheese"

    def price(self):
        return 10


class BurritoNoOnion(Burrito):
    def name(self):
        return "burrito, no onion"


class BurritoExtraCheeseNoOnion(BurritoExtraCheese):
    def name(self):
        return "burrito, extra cheese, no onion"


for order in [Burrito(), BurritoExtraCheese(), BurritoNoOnion(), BurritoExtraCheeseNoOnion()]:
    print(f"{order.name()}: ${order.price()}")
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
class Burrito {
  name() { return "burrito"; }
  price() { return 9; }
}

class BurritoExtraCheese extends Burrito {
  name() { return "burrito, extra cheese"; }
  price() { return 10; }
}

class BurritoNoOnion extends Burrito {
  name() { return "burrito, no onion"; }
}

class BurritoExtraCheeseNoOnion extends BurritoExtraCheese {
  name() { return "burrito, extra cheese, no onion"; }
}

for (const order of [new Burrito(), new BurritoExtraCheese(), new BurritoNoOnion(), new BurritoExtraCheeseNoOnion()]) {
  console.log(`${order.name()}: ${order.price()}`);
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
class Burrito {
  name(): string { return "burrito"; }
  price(): number { return 9; }
}

class BurritoExtraCheese extends Burrito {
  name(): string { return "burrito, extra cheese"; }
  price(): number { return 10; }
}

class BurritoNoOnion extends Burrito {
  name(): string { return "burrito, no onion"; }
}

class BurritoExtraCheeseNoOnion extends BurritoExtraCheese {
  name(): string { return "burrito, extra cheese, no onion"; }
}

const orders: Burrito[] = [new Burrito(), new BurritoExtraCheese(), new BurritoNoOnion(), new BurritoExtraCheeseNoOnion()];
for (const order of orders) {
  console.log(`${order.name()}: ${order.price()}`);
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10

It works, and each class is tiny. Now count. Two options give four classes for the burrito: plain, cheese, no onion, both. The taco and the quesadilla need their own four, so twelve. Add guacamole as a third option and every item has eight combinations: twenty-four classes. When the grilled veggie wrap arrives, someone will write a class called GrilledVeggieWrapWithExtraCheeseNoOnion, and someone else will have to find it.

  • The symptom: class names that read like orders, and a count that doubles with each new option. This is called a class explosion.
  • The cause: inheritance fixes what a class is when you write the code, so every combination has to be written ahead of time. The options don't combine; only classes that someone already wrote do.

What would you try?

Keep adding subclasses. That's the explosion. Guacamole alone means twelve new classes, and a price change to extra cheese means editing every class that has it.

Flags on one class: Burrito(extraCheese: true, noOnion: true). Much better: one class. But every new option is a new constructor parameter, a new if in the name and another in the price. That's the growing if chain from Code Smells, back again.

One big base class that knows every option, for every item. That's one class with many jobs, the third smell from Code Smells.

What would help is if an extra were a thing of its own, with a name and a price, and an order could hold as many of them as the customer asked for.

The idea: build from parts

Instead of a burrito that is a cheese burrito, make a menu item that has extras. An Extra is a small object with a name and a price; a MenuItem holds a list of them, and works out its name and price by asking each one. This is composition: building an object out of other objects it holds. Inheritance says what a class is, and it's decided when the code is written. Composition says what an object has, and it's decided when the object is built, so any mix of parts works without anyone writing a class for it.

Two ways to build menu items. Left: a family tree of subclasses (BurritoExtraCheese, BurritoNoOnion, BurritoExtraCheeseNoOnion and a faded crowd), "24 classes for 3 items and 3 options". Right: one MenuItem, burrito $9, holding two Extra parts, "1 part per option"

Extra cheese = new Extra("extra cheese", 1);
Extra noOnion = new Extra("no onion", 0);
List<MenuItem> orders = new List<MenuItem>
{
    new MenuItem("burrito", 9, new List<Extra>()),
    new MenuItem("burrito", 9, new List<Extra> { cheese }),
    new MenuItem("burrito", 9, new List<Extra> { noOnion }),
    new MenuItem("burrito", 9, new List<Extra> { cheese, noOnion })
};
foreach (MenuItem order in orders)
{
    Console.WriteLine(quot;{order.Name()}: ${order.Price()}");
}

// An extra is a part of its own: a name and a price.
record Extra(string Name, int Price);

// A menu item has extras. Any mix works, and nobody writes a class for it.
class MenuItem
{
    private string name;
    private int price;
    private List<Extra> extras;

    public MenuItem(string name, int price, List<Extra> extras)
    {
        this.name = name;
        this.price = price;
        this.extras = extras;
    }

    public string Name() => string.Join(", ", new List<string> { name }.Concat(extras.Select(extra => extra.Name)));
    public int Price() => price + extras.Sum(extra => extra.Price);
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
// An extra is a part of its own: a name and a price.
record Extra(String name, int price) {}

// A menu item has extras. Any mix works, and nobody writes a class for it.
class MenuItem {
    private String name;
    private int price;
    private List<Extra> extras;

    MenuItem(String name, int price, List<Extra> extras) {
        this.name = name;
        this.price = price;
        this.extras = extras;
    }

    String name() {
        String result = name;
        for (Extra extra : extras) { result += ", " + extra.name(); }
        return result;
    }

    int price() {
        int total = price;
        for (Extra extra : extras) { total += extra.price(); }
        return total;
    }
}

void main() {
    Extra cheese = new Extra("extra cheese", 1);
    Extra noOnion = new Extra("no onion", 0);
    List<MenuItem> orders = List.of(
        new MenuItem("burrito", 9, List.of()),
        new MenuItem("burrito", 9, List.of(cheese)),
        new MenuItem("burrito", 9, List.of(noOnion)),
        new MenuItem("burrito", 9, List.of(cheese, noOnion)));
    for (MenuItem order : orders) {
        IO.println(order.name() + ": quot; + order.price());
    }
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
class Extra:
    """An extra is a part of its own: a name and a price."""

    def __init__(self, name, price):
        self.name = name
        self.price = price


class MenuItem:
    """A menu item has extras. Any mix works, and nobody writes a class for it."""

    def __init__(self, name, price, extras):
        self.base_name = name
        self.base_price = price
        self.extras = extras

    def name(self):
        return ", ".join([self.base_name] + [extra.name for extra in self.extras])

    def price(self):
        return self.base_price + sum(extra.price for extra in self.extras)


cheese = Extra("extra cheese", 1)
no_onion = Extra("no onion", 0)
orders = [
    MenuItem("burrito", 9, []),
    MenuItem("burrito", 9, [cheese]),
    MenuItem("burrito", 9, [no_onion]),
    MenuItem("burrito", 9, [cheese, no_onion]),
]
for order in orders:
    print(f"{order.name()}: ${order.price()}")
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
// An extra is a part of its own: a name and a price.
class Extra {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

// A menu item has extras. Any mix works, and nobody writes a class for it.
class MenuItem {
  constructor(name, price, extras) {
    this.baseName = name;
    this.basePrice = price;
    this.extras = extras;
  }

  name() { return [this.baseName, ...this.extras.map((extra) => extra.name)].join(", "); }
  price() { return this.extras.reduce((total, extra) => total + extra.price, this.basePrice); }
}

const cheese = new Extra("extra cheese", 1);
const noOnion = new Extra("no onion", 0);
const orders = [
  new MenuItem("burrito", 9, []),
  new MenuItem("burrito", 9, [cheese]),
  new MenuItem("burrito", 9, [noOnion]),
  new MenuItem("burrito", 9, [cheese, noOnion]),
];
for (const order of orders) {
  console.log(`${order.name()}: ${order.price()}`);
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10
// An extra is a part of its own: a name and a price.
class Extra {
  name: string;
  price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }
}

// A menu item has extras. Any mix works, and nobody writes a class for it.
class MenuItem {
  baseName: string;
  basePrice: number;
  extras: Extra[];

  constructor(name: string, price: number, extras: Extra[]) {
    this.baseName = name;
    this.basePrice = price;
    this.extras = extras;
  }

  name(): string { return [this.baseName, ...this.extras.map((extra) => extra.name)].join(", "); }
  price(): number { return this.extras.reduce((total, extra) => total + extra.price, this.basePrice); }
}

const cheese = new Extra("extra cheese", 1);
const noOnion = new Extra("no onion", 0);
const orders = [
  new MenuItem("burrito", 9, []),
  new MenuItem("burrito", 9, [cheese]),
  new MenuItem("burrito", 9, [noOnion]),
  new MenuItem("burrito", 9, [cheese, noOnion]),
];
for (const order of orders) {
  console.log(`${order.name()}: ${order.price()}`);
}
burrito: $9
burrito, extra cheese: $10
burrito, no onion: $9
burrito, extra cheese, no onion: $10

Same four lines, and two classes instead of four. Guacamole is one line, new Extra("guacamole", 2), and it works on every item at once: a taco with guacamole is new MenuItem("taco", 4, [guacamole]). The grilled veggie wrap is one more MenuItem, and nobody has to name GrilledVeggieWrapWithExtraCheeseNoOnion.

Try it. Make a guacamole extra at $2 and print a quesadilla ($7) with guacamole and extra cheese. It should print quesadilla, guacamole, extra cheese: $10.

Where the languages differ. C# and Java write Extra as a one-line record, a class for holding values. Python, JavaScript and TypeScript write it as a small class with two fields.

How it got its name

The 1994 book that named the classic patterns put this beside program to an interface on its first pages: favor composition over inheritance. You'll also hear it as "prefer composition to inheritance", or "composition over inheritance". Several patterns in this course are this idea with a name: a Strategy is an object that has a rule it can swap, and a Decorator has the thing it adds a feature to.

When inheritance is still right

"Prefer" isn't "never". Inheritance is a good fit when:

  • It's a true is-a with nothing to combine. Every menu item, plain or not, is something with a name and a price; a shared base class or interface for that is fine.
  • The kinds don't mix. An e-bike is a bike, and it will never also be a scooter.
  • A framework asks for it, such as a test class that extends the framework's base class.

Reach for composition when options combine, when an object's parts should change while the program runs, or when a subclass would inherit code it doesn't want.

Check yourself

2 questions to try on the lesson page.

So what

When options multiply, don't write a class for every combination. Make each option a part, and build the object from the parts it has. A new option is then one new part, and it works with everything that's already there.

Key terms

Cheat sheets