Skip to main content

Composition vs Inheritance — Favor Composition

Editorial

Introduction

A shop sends notifications by email, by SMS and by push, and each one can be written as plain text, as HTML or as JSON. Built with inheritance, every pairing becomes its own subclass: an HtmlEmailSender, a JsonSmsSender, and so on, nine of them, each repeating some other class's code. Built with composition, there is one notification service that holds a channel and a formatter, and three of each to choose from.

The advice comes from the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software, whose four authors are often called the Gang of Four. Wikipedia's article on the book quotes the principle as they wrote it: "Favor 'object composition' over 'class inheritance'." Composition here means an object holding other objects that do part of its work, and calling them; Composition — Has-A with Dependent Lifecycle covers the UML relationship of the same name, which is one form of it.

Wikipedia's article on the principle describes composition over inheritance as "a common design pattern that tries to achieve code reuse without requiring inheritance", and it is careful about the other side: "many problems that are easily solved with inheritance are difficult to solve using only composition; as a result, inheritance and object composition typically work hand-in-hand, as discussed in the book Design Patterns (1994)."

The picture shows the notifications built both ways:

Composition vs inheritance, favor composition: reuse by holding parts that do the work, before inheriting from a base, on a notification system of 3 channels, Email, Sms and Push, and 3 formats, Plain, Html and Json. Inheritance, a subclass for every pair: NotificationSender over 9 subclasses, from PlainEmailSender to JsonPushSender, counted as 3 x 3 = 9 subclasses, and a 4th channel would add 3 more; each extends it, repeating a channel's or a format's code. Composition, pieces that combine: a NotificationService that holds one channel and one formatter, any channel of EmailChannel, SmsChannel and PushChannel and any formatter of PlainFormatter, HtmlFormatter and JsonFormatter, counted as 3 + 3 = 6 classes and a service, and a 4th channel would add 1 more. The program's three sends: Email + Html gives the text in an HTML paragraph, Email + Plain the plain text, Sms + Json the text as JSON. Below, three more things the choice decides. A fragile base class: the same EmailSender under base v1 sends the HTML paragraph, and under base v2, whose send no longer calls the hook, the plain text, with no error. Fixed when written: a subclass is picked when the code is written, and the service took Plain and Json while it ran. Is it a real is-a: Dog is-a Animal, inherit; Car has-a Engine, compose; only reusing code, compose.

The Fragile Base Class

The Gang of Four's book names the danger, as Wikipedia quotes it: "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". Wikipedia's article on the fragile base class problem describes what can follow: base classes are "considered "fragile" because seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction." Here is a small case of it. An email sender changes how messages look by overriding a hook, format_message, that the base class calls.

# A notification sender, and an email sender that changes how a message looks
# by overriding the format_message hook the base class calls.


class NotificationSender:
    def send(self, to: str, text: str) -> str:
        return f"to {to}: {self.format_message(text)}"

    def format_message(self, text: str) -> str:
        return text


class EmailSender(NotificationSender):
    # Relies on send() calling format_message(): a detail inside the base class
    def format_message(self, text: str) -> str:
        return f"<p>{text}</p>"


def main() -> None:
    print(EmailSender().send("ann@shop.example", "Your order shipped"))


if __name__ == "__main__":
    main()
// A notification sender, and an email sender that changes how a message looks
// by overriding the formatMessage hook the base class calls.
class NotificationSender {
    String send(String to, String text) {
        return "to " + to + ": " + formatMessage(text);
    }

    String formatMessage(String text) {
        return text;
    }
}

class EmailSender extends NotificationSender {
    // Relies on send() calling formatMessage(): a detail inside the base class
    @Override
    String formatMessage(String text) {
        return "<p>" + text + "</p>";
    }
}

public class Notifications {
    public static void main(String[] args) {
        EmailSender sender = new EmailSender();
        System.out.println(sender.send("ann@shop.example", "Your order shipped"));
    }
}
#include <iostream>
#include <string>

// A notification sender, and an email sender that changes how a message looks
// by overriding the formatMessage hook the base class calls.
class NotificationSender {
public:
    virtual ~NotificationSender() = default;

    std::string send(const std::string& to, const std::string& text) const {
        return "to " + to + ": " + formatMessage(text);
    }

    virtual std::string formatMessage(const std::string& text) const { return text; }
};

class EmailSender : public NotificationSender {
public:
    // Relies on send() calling formatMessage(): a detail inside the base class
    std::string formatMessage(const std::string& text) const override {
        return "<p>" + text + "</p>";
    }
};

int main() {
    EmailSender sender;
    std::cout << sender.send("ann@shop.example", "Your order shipped") << "\n";
}
// A notification sender, and an email sender that changes how a message looks
// by overriding the formatMessage hook the base class calls.
class NotificationSender {
  send(to: string, text: string): string {
    return `to ${to}: ${this.formatMessage(text)}`;
  }

  formatMessage(text: string): string {
    return text;
  }
}

class EmailSender extends NotificationSender {
  // Relies on send() calling formatMessage(): a detail inside the base class
  override formatMessage(text: string): string {
    return `<p>${text}</p>`;
  }
}

function main(): void {
  console.log(new EmailSender().send("ann@shop.example", "Your order shipped"));
}

main();
using System;

// A notification sender, and an email sender that changes how a message looks
// by overriding the FormatMessage hook the base class calls.
public class NotificationSender
{
    public string Send(string to, string text) => $"to {to}: {FormatMessage(text)}";

    public virtual string FormatMessage(string text) => text;
}

public class EmailSender : NotificationSender
{
    // Relies on Send() calling FormatMessage(): a detail inside the base class
    public override string FormatMessage(string text) => $"<p>{text}</p>";
}

public class Notifications
{
    public static void Main()
    {
        var sender = new EmailSender();
        Console.WriteLine(sender.Send("ann@shop.example", "Your order shipped"));
    }
}
package main

import "fmt"

// A notification sender, and an email sender that changes how a message looks
// by supplying the formatting hook the base type calls.

// MessageFormat is the hook. Go has no inheritance, so the base type calls its hook
// through an interface, and the email sender supplies itself as that hook.
type MessageFormat interface {
	FormatMessage(text string) string
}

type NotificationSender struct {
	hook MessageFormat
}

func (s NotificationSender) Send(to, text string) string {
	return "to " + to + ": " + s.hook.FormatMessage(text)
}

func (s NotificationSender) FormatMessage(text string) string {
	return text
}

type EmailSender struct {
	NotificationSender
}

func NewEmailSender() *EmailSender {
	e := &EmailSender{}
	e.hook = e
	return e
}

// FormatMessage relies on Send calling the hook: a detail inside NotificationSender.
func (e *EmailSender) FormatMessage(text string) string {
	return "<p>" + text + "</p>"
}

func main() {
	fmt.Println(NewEmailSender().Send("ann@shop.example", "Your order shipped"))
}

It prints:

to ann@shop.example: <p>Your order shipped</p>

EmailSender works only because send happens to call format_message. That call is a detail inside the base class, and the base class never promised to keep it. Now suppose a later version of NotificationSender tidies send up so that it prepares the text in a new private method and no longer calls the hook. Nothing in EmailSender changes, and it still compiles. Run against the new base class, the same program prints:

to ann@shop.example: Your order shipped

The HTML is gone, with no error and no warning. That was run in all six languages with the base class changed and the subclass untouched, and every one printed the plain text. Wikipedia's own example is harsher: after a change to the base class, the subclass's override and a base method keep calling each other, an infinite recursion that ends in a stack overflow. The article calls it "good practice for super-classes to avoid changing calls to dynamically-bound methods", which is the change version 2 made, and it quotes Joshua Bloch's Effective Java: "Design and document for inheritance or else prohibit it". Java's final, and C#'s sealed, exist to prohibit it.

When Behaviors Multiply

Here is the same system built by composition. The service holds a channel and a formatter, each behind a small interface of its own.

# The same notifications built by composition: a service holds a channel and a
# formatter, each behind its own small interface, and either can be swapped.
from abc import ABC, abstractmethod


class DeliveryChannel(ABC):
    @abstractmethod
    def deliver(self, to: str, body: str) -> str: ...


class MessageFormatter(ABC):
    @abstractmethod
    def format(self, text: str) -> str: ...


class EmailChannel(DeliveryChannel):
    def deliver(self, to: str, body: str) -> str:
        return f"email to {to}: {body}"


class SmsChannel(DeliveryChannel):
    def deliver(self, to: str, body: str) -> str:
        return f"sms to {to}: {body}"


class PushChannel(DeliveryChannel):
    def deliver(self, to: str, body: str) -> str:
        return f"push to {to}: {body}"


class PlainFormatter(MessageFormatter):
    def format(self, text: str) -> str:
        return text


class HtmlFormatter(MessageFormatter):
    def format(self, text: str) -> str:
        return f"<p>{text}</p>"


class JsonFormatter(MessageFormatter):
    def format(self, text: str) -> str:
        return f'{{"text": "{text}"}}'


class NotificationService:
    def __init__(self, channel: DeliveryChannel, formatter: MessageFormatter) -> None:
        self._channel = channel
        self._formatter = formatter

    def set_channel(self, channel: DeliveryChannel) -> None:
        self._channel = channel

    def set_formatter(self, formatter: MessageFormatter) -> None:
        self._formatter = formatter

    def send(self, to: str, text: str) -> str:
        return self._channel.deliver(to, self._formatter.format(text))


def main() -> None:
    service = NotificationService(EmailChannel(), HtmlFormatter())
    print(service.send("ann@shop.example", "Your order shipped"))
    service.set_formatter(PlainFormatter())  # swapped while the program runs
    print(service.send("ann@shop.example", "Your order shipped"))
    service.set_channel(SmsChannel())
    service.set_formatter(JsonFormatter())
    print(service.send("+1 555 0100", "Your order shipped"))


if __name__ == "__main__":
    main()
// The same notifications built by composition: a service holds a channel and a
// formatter, each behind its own small interface, and either can be swapped.
interface DeliveryChannel {
    String deliver(String to, String body);
}

interface MessageFormatter {
    String format(String text);
}

class EmailChannel implements DeliveryChannel {
    public String deliver(String to, String body) {
        return "email to " + to + ": " + body;
    }
}

class SmsChannel implements DeliveryChannel {
    public String deliver(String to, String body) {
        return "sms to " + to + ": " + body;
    }
}

class PushChannel implements DeliveryChannel {
    public String deliver(String to, String body) {
        return "push to " + to + ": " + body;
    }
}

class PlainFormatter implements MessageFormatter {
    public String format(String text) {
        return text;
    }
}

class HtmlFormatter implements MessageFormatter {
    public String format(String text) {
        return "<p>" + text + "</p>";
    }
}

class JsonFormatter implements MessageFormatter {
    public String format(String text) {
        return "{\"text\": \"" + text + "\"}";
    }
}

class NotificationService {
    private DeliveryChannel channel;
    private MessageFormatter formatter;

    NotificationService(DeliveryChannel channel, MessageFormatter formatter) {
        this.channel = channel;
        this.formatter = formatter;
    }

    void setChannel(DeliveryChannel channel) {
        this.channel = channel;
    }

    void setFormatter(MessageFormatter formatter) {
        this.formatter = formatter;
    }

    String send(String to, String text) {
        return channel.deliver(to, formatter.format(text));
    }
}

public class Notifications {
    public static void main(String[] args) {
        NotificationService service =
            new NotificationService(new EmailChannel(), new HtmlFormatter());
        System.out.println(service.send("ann@shop.example", "Your order shipped"));
        service.setFormatter(new PlainFormatter()); // swapped while the program runs
        System.out.println(service.send("ann@shop.example", "Your order shipped"));
        service.setChannel(new SmsChannel());
        service.setFormatter(new JsonFormatter());
        System.out.println(service.send("+1 555 0100", "Your order shipped"));
    }
}
#include <iostream>
#include <memory>
#include <string>
#include <utility>

// The same notifications built by composition: a service holds a channel and a
// formatter, each behind its own small interface, and either can be swapped.
class DeliveryChannel {
public:
    virtual ~DeliveryChannel() = default;
    virtual std::string deliver(const std::string& to,
                                const std::string& body) const = 0;
};

class MessageFormatter {
public:
    virtual ~MessageFormatter() = default;
    virtual std::string format(const std::string& text) const = 0;
};

class EmailChannel : public DeliveryChannel {
public:
    std::string deliver(const std::string& to,
                        const std::string& body) const override {
        return "email to " + to + ": " + body;
    }
};

class SmsChannel : public DeliveryChannel {
public:
    std::string deliver(const std::string& to,
                        const std::string& body) const override {
        return "sms to " + to + ": " + body;
    }
};

class PushChannel : public DeliveryChannel {
public:
    std::string deliver(const std::string& to,
                        const std::string& body) const override {
        return "push to " + to + ": " + body;
    }
};

class PlainFormatter : public MessageFormatter {
public:
    std::string format(const std::string& text) const override { return text; }
};

class HtmlFormatter : public MessageFormatter {
public:
    std::string format(const std::string& text) const override {
        return "<p>" + text + "</p>";
    }
};

class JsonFormatter : public MessageFormatter {
public:
    std::string format(const std::string& text) const override {
        return "{\"text\": \"" + text + "\"}";
    }
};

class NotificationService {
public:
    NotificationService(std::unique_ptr<DeliveryChannel> channel,
                        std::unique_ptr<MessageFormatter> formatter)
        : channel_(std::move(channel)), formatter_(std::move(formatter)) {}

    void setChannel(std::unique_ptr<DeliveryChannel> channel) {
        channel_ = std::move(channel);
    }

    void setFormatter(std::unique_ptr<MessageFormatter> formatter) {
        formatter_ = std::move(formatter);
    }

    std::string send(const std::string& to, const std::string& text) const {
        return channel_->deliver(to, formatter_->format(text));
    }

private:
    std::unique_ptr<DeliveryChannel> channel_;
    std::unique_ptr<MessageFormatter> formatter_;
};

int main() {
    NotificationService service(std::make_unique<EmailChannel>(),
                                std::make_unique<HtmlFormatter>());
    std::cout << service.send("ann@shop.example", "Your order shipped") << "\n";
    service.setFormatter(std::make_unique<PlainFormatter>());  // swapped while it runs
    std::cout << service.send("ann@shop.example", "Your order shipped") << "\n";
    service.setChannel(std::make_unique<SmsChannel>());
    service.setFormatter(std::make_unique<JsonFormatter>());
    std::cout << service.send("+1 555 0100", "Your order shipped") << "\n";
}
// The same notifications built by composition: a service holds a channel and a
// formatter, each behind its own small interface, and either can be swapped.
interface DeliveryChannel {
  deliver(to: string, body: string): string;
}

interface MessageFormatter {
  format(text: string): string;
}

class EmailChannel implements DeliveryChannel {
  deliver(to: string, body: string): string {
    return `email to ${to}: ${body}`;
  }
}

class SmsChannel implements DeliveryChannel {
  deliver(to: string, body: string): string {
    return `sms to ${to}: ${body}`;
  }
}

class PushChannel implements DeliveryChannel {
  deliver(to: string, body: string): string {
    return `push to ${to}: ${body}`;
  }
}

class PlainFormatter implements MessageFormatter {
  format(text: string): string {
    return text;
  }
}

class HtmlFormatter implements MessageFormatter {
  format(text: string): string {
    return `<p>${text}</p>`;
  }
}

class JsonFormatter implements MessageFormatter {
  format(text: string): string {
    return `{"text": "${text}"}`;
  }
}

class NotificationService {
  private channel: DeliveryChannel;
  private formatter: MessageFormatter;

  constructor(channel: DeliveryChannel, formatter: MessageFormatter) {
    this.channel = channel;
    this.formatter = formatter;
  }

  setChannel(channel: DeliveryChannel): void {
    this.channel = channel;
  }

  setFormatter(formatter: MessageFormatter): void {
    this.formatter = formatter;
  }

  send(to: string, text: string): string {
    return this.channel.deliver(to, this.formatter.format(text));
  }
}

function main(): void {
  const service = new NotificationService(new EmailChannel(), new HtmlFormatter());
  console.log(service.send("ann@shop.example", "Your order shipped"));
  service.setFormatter(new PlainFormatter()); // swapped while the program runs
  console.log(service.send("ann@shop.example", "Your order shipped"));
  service.setChannel(new SmsChannel());
  service.setFormatter(new JsonFormatter());
  console.log(service.send("+1 555 0100", "Your order shipped"));
}

main();
using System;

// The same notifications built by composition: a service holds a channel and a
// formatter, each behind its own small interface, and either can be swapped.
public interface IDeliveryChannel
{
    string Deliver(string to, string body);
}

public interface IMessageFormatter
{
    string Format(string text);
}

public class EmailChannel : IDeliveryChannel
{
    public string Deliver(string to, string body) => $"email to {to}: {body}";
}

public class SmsChannel : IDeliveryChannel
{
    public string Deliver(string to, string body) => $"sms to {to}: {body}";
}

public class PushChannel : IDeliveryChannel
{
    public string Deliver(string to, string body) => $"push to {to}: {body}";
}

public class PlainFormatter : IMessageFormatter
{
    public string Format(string text) => text;
}

public class HtmlFormatter : IMessageFormatter
{
    public string Format(string text) => $"<p>{text}</p>";
}

public class JsonFormatter : IMessageFormatter
{
    public string Format(string text) => "{\"text\": \"" + text + "\"}";
}

public class NotificationService
{
    private IDeliveryChannel channel;
    private IMessageFormatter formatter;

    public NotificationService(IDeliveryChannel channel, IMessageFormatter formatter)
    {
        this.channel = channel;
        this.formatter = formatter;
    }

    public void SetChannel(IDeliveryChannel channel)
    {
        this.channel = channel;
    }

    public void SetFormatter(IMessageFormatter formatter)
    {
        this.formatter = formatter;
    }

    public string Send(string to, string text) =>
        channel.Deliver(to, formatter.Format(text));
}

public class Notifications
{
    public static void Main()
    {
        var service = new NotificationService(new EmailChannel(), new HtmlFormatter());
        Console.WriteLine(service.Send("ann@shop.example", "Your order shipped"));
        service.SetFormatter(new PlainFormatter()); // swapped while the program runs
        Console.WriteLine(service.Send("ann@shop.example", "Your order shipped"));
        service.SetChannel(new SmsChannel());
        service.SetFormatter(new JsonFormatter());
        Console.WriteLine(service.Send("+1 555 0100", "Your order shipped"));
    }
}
package main

import "fmt"

// The same notifications built by composition: a service holds a channel and a
// formatter, each behind its own small interface, and either can be swapped.

type DeliveryChannel interface {
	Deliver(to, body string) string
}

type MessageFormatter interface {
	Format(text string) string
}

type EmailChannel struct{}

func (EmailChannel) Deliver(to, body string) string {
	return "email to " + to + ": " + body
}

type SmsChannel struct{}

func (SmsChannel) Deliver(to, body string) string {
	return "sms to " + to + ": " + body
}

type PushChannel struct{}

func (PushChannel) Deliver(to, body string) string {
	return "push to " + to + ": " + body
}

type PlainFormatter struct{}

func (PlainFormatter) Format(text string) string {
	return text
}

type HtmlFormatter struct{}

func (HtmlFormatter) Format(text string) string {
	return "<p>" + text + "</p>"
}

type JsonFormatter struct{}

func (JsonFormatter) Format(text string) string {
	return `{"text": "` + text + `"}`
}

type NotificationService struct {
	channel   DeliveryChannel
	formatter MessageFormatter
}

func NewNotificationService(
	c DeliveryChannel, f MessageFormatter,
) *NotificationService {
	return &NotificationService{channel: c, formatter: f}
}

func (s *NotificationService) SetChannel(c DeliveryChannel) {
	s.channel = c
}

func (s *NotificationService) SetFormatter(f MessageFormatter) {
	s.formatter = f
}

func (s *NotificationService) Send(to, text string) string {
	return s.channel.Deliver(to, s.formatter.Format(text))
}

func main() {
	service := NewNotificationService(EmailChannel{}, HtmlFormatter{})
	fmt.Println(service.Send("ann@shop.example", "Your order shipped"))
	service.SetFormatter(PlainFormatter{}) // swapped while the program runs
	fmt.Println(service.Send("ann@shop.example", "Your order shipped"))
	service.SetChannel(SmsChannel{})
	service.SetFormatter(JsonFormatter{})
	fmt.Println(service.Send("+1 555 0100", "Your order shipped"))
}

It prints:

email to ann@shop.example: <p>Your order shipped</p>
email to ann@shop.example: Your order shipped
sms to +1 555 0100: {"text": "Your order shipped"}

Three channels and three formatters make nine combinations from six small classes and one service. With inheritance the same nine combinations need nine subclasses, and each new channel adds one subclass for every format, three more here, where composition adds one class. The HTML formatting is written once, in HtmlFormatter, and any channel can use it, which is what DRY — Don't Repeat Yourself asks for.

The book calls inheritance white-box reuse, because a subclass can often see its parent's insides, and object composition black-box reuse, because "no internal details of composed objects need be visible in the code using them". The service here is black-box reuse: it calls format and deliver through their interfaces, so each class can change how it works inside without breaking the others, as long as it still does what its interface promises.

Changing Behavior While the Program Runs

A subclass is chosen when the code is written: an EmailSender is an email sender for as long as it exists. The service in the program above was built with an email channel and an HTML formatter, then given a plain formatter, then an SMS channel and a JSON formatter, all while it was running. That is what holding a part instead of inheriting it makes possible.

The channel and the formatter here are interchangeable behaviors behind an interface, which is the idea of Strategy Pattern — Swappable Algorithms. Decorator Pattern — Adding Behavior Dynamically uses composition another way: a decorator holds an object with the same interface as its own, and adds behavior before or after it passes each call on.

When Inheritance Is the Right Choice

Favoring composition does not mean never inheriting. Inheritance is the right tool in a few common cases.

A real is-a relationship. A dog is an animal, and a Dog class can extend Animal as long as every use of an animal still works with a dog, which is the test L — Liskov Substitution Principle gives. Inheritance — Code Reuse & Hierarchies covers this kind of hierarchy.

A base class designed for extension. Bloch's advice cuts both ways: a base class that documents which methods may be overridden, and when it calls them, is built to be extended.

A framework that asks for it. Some frameworks are built around subclassing. Python's testing library is one: its documentation says "A test case is created by subclassing unittest.TestCase."

A fixed sequence of steps. When an algorithm's outline is the same for every variant and only some steps differ, Template Method Pattern — Algorithm Skeleton puts the outline in a base class and lets subclasses fill in the steps.

Common Mistakes

Inheriting only to reuse code. Java's own Stack extends Vector, so a stack also has every method a vector has, including ones that insert or remove at any position, which a stack should not allow. Its documentation points elsewhere: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class." A stack that holds a list as a private field and offers only push, pop and peek has no such holes.

Deep hierarchies. A chain such as Vehicle, MotorVehicle, FourWheelVehicle, Car, ElectricCar means that to understand the last class you read all the others, and a change near the top reaches everything below it. Pulling the ideas that vary, such as the engine or the drive, out into parts that a single Vehicle holds is usually easier to follow.

Composing everything. Turning a plain, stable is-a hierarchy into a set of interfaces and parts adds pieces without adding flexibility anyone needs. As Wikipedia's article says, some problems are easily solved with inheritance and hard to solve with composition alone.

Deciding

A few questions, asked in order, settle most cases.

  1. Is it a real is-a relationship, where every use of the parent still works with the child? If not, compose.
  2. Was the base class designed and documented for extension? If not, compose, or ask its owner.
  3. Does the behavior vary along more than one dimension, such as channel and format? Then compose, or the classes multiply.
  4. Must the behavior change while the program runs? Then compose.

If the answers point to inheritance, use it with a shallow hierarchy. Refactoring: Deep Inheritance → Composition walks through moving an existing hierarchy over to composition. Checkpoint: Beyond SOLID comes next, ten short situations on these principles.

Key Takeaways

  • Favor composition: build behavior from objects a class holds and calls, and inherit when there is a real is-a relationship.
  • A subclass depends on details inside its base class, so a change there can break it silently: the fragile base class.
  • Inheritance multiplies classes when behavior varies along several dimensions; composition adds one small class per new option, and its parts can be swapped while the program runs.
  • Inheritance is right for real is-a relationships, bases designed for extension, frameworks built around subclassing, and fixed sequences of steps.