Skip to lesson

Favouring composition when designing classes

ShopLite must send order messages by email, SMS and push, in any mix a customer chooses. One subclass per mix works for two channels and falls apart at four. This lesson shows the way out.

The subclass explosion

A subclass explosion happens when every mix of features needs its own subclass, so the class count grows far faster than the feature count: n features can need 2^n - 1 subclasses.

With inheritance, each mix of channels needs its own class. Below are two of those classes, then a count of how fast they multiply.

Example 1 · Inheritance: one class per combination

SubclassExplosionDemo.javaJava
record Customer(String name, String email, String phone) {}
class EmailNotifier {    void send(Customer c, String text) {        System.out.println("Email to " + c.email() + ": " + text);    }}
class SmsNotifier {    void send(Customer c, String text) {        System.out.println("SMS to " + c.phone() + ": " + text);    }}
// Java allows one parent class, so the SMS code is copied inclass EmailSmsNotifier extends EmailNotifier {    @Override    void send(Customer c, String text) {        super.send(c, text);        System.out.println("SMS to " + c.phone() + ": " + text);    }}
class EmailPushNotifier extends EmailNotifier {    @Override    void send(Customer c, String text) {        super.send(c, text);        System.out.println("Push to " + c.name() + "'s app: " + text);    }}
public class SubclassExplosionDemo {    public static void main(String[] args) {        Customer asha = new Customer("Asha", "asha@mail.com", "9876543210");        new EmailSmsNotifier().send(asha, "ORD-11 confirmed");        new EmailPushNotifier().send(asha, "ORD-12 shipped");
        for (int channels = 3; channels <= 4; channels++) {            int combinations = (1 << channels) - 1;      // every non-empty mix of channels            System.out.println(channels + " channels -> " + combinations + " notifier classes");        }    }}
Output
Email to asha@mail.com: ORD-11 confirmed
SMS to 9876543210: ORD-11 confirmed
Email to asha@mail.com: ORD-12 shipped
Push to Asha's app: ORD-12 shipped
3 channels -> 7 notifier classes
4 channels -> 15 notifier classes

What this code does

  • EmailSmsNotifier reuses email through super.send, but the SMS line is a copy of SmsNotifier's code, because a class can have only one parent.
  • The loop counts the non-empty mixes of channels: 2 to the power n, minus 1. Each one would be its own class.

3 channels need 7 classes and 4 channels need 15. Inheritance also forces copying: Java allows one parent class, so EmailSmsNotifier can extend EmailNotifier but must copy the SMS code, and a fix to the SMS text has to be made in every copy.

Predict the output

Count the subclasses

Each line counts the subclasses needed. What does it print?

Round 1 of 2

int channels = 3;
int subclasses = (1 << channels) - 1;
System.out.println(subclasses);

Rebuilding it with a list of channels

Composition means a class gets its behaviour by holding other objects (has-a) and calling them, instead of inheriting it from a parent class (is-a).

Now each channel is one small class behind a NotificationChannel interface, and one OrderNotifier holds a list of channels. Below, three different mixes come from the same classes.

Example 2 · Composition: one notifier holding channels

ComposedNotifierDemo.javaJava
import java.util.List;
record Customer(String name, String email, String phone) {}
interface NotificationChannel {    void send(Customer c, String text);}
class EmailChannel implements NotificationChannel {    public void send(Customer c, String text) {        System.out.println("Email to " + c.email() + ": " + text);    }}
class SmsChannel implements NotificationChannel {    public void send(Customer c, String text) {        System.out.println("SMS to " + c.phone() + ": " + text);    }}
class PushChannel implements NotificationChannel {    public void send(Customer c, String text) {        System.out.println("Push to " + c.name() + "'s app: " + text);    }}
// One notifier class for every combination: it HAS channelsclass OrderNotifier {    private final List<NotificationChannel> channels;
    OrderNotifier(List<NotificationChannel> channels) {        this.channels = List.copyOf(channels);    }
    void send(Customer c, String text) {        for (NotificationChannel channel : channels) {            channel.send(c, text);        }    }}
public class ComposedNotifierDemo {    public static void main(String[] args) {        Customer asha = new Customer("Asha", "asha@mail.com", "9876543210");
        OrderNotifier emailSms = new OrderNotifier(List.of(new EmailChannel(), new SmsChannel()));        OrderNotifier emailPush = new OrderNotifier(List.of(new EmailChannel(), new PushChannel()));        OrderNotifier all = new OrderNotifier(List.of(new EmailChannel(), new SmsChannel(), new PushChannel()));
        emailSms.send(asha, "ORD-11 confirmed");        emailPush.send(asha, "ORD-12 shipped");        all.send(asha, "ORD-13 delivered");    }}
Output
Email to asha@mail.com: ORD-11 confirmed
SMS to 9876543210: ORD-11 confirmed
Email to asha@mail.com: ORD-12 shipped
Push to Asha's app: ORD-12 shipped
Email to asha@mail.com: ORD-13 delivered
SMS to 9876543210: ORD-13 delivered
Push to Asha's app: ORD-13 delivered

What this code does

  • The first four lines match Example 1 exactly, but there is no EmailSmsNotifier or EmailPushNotifier class any more: each mix is just a different list.
  • The SMS code lives in one place, SmsChannel. A fix there reaches every notifier that uses SMS.

Sending a message is a loop over that list. The class count grows with the number of channels, not with their combinations: 3 channel classes plus 1 notifier cover all 7 mixes.

Adding WhatsApp is one new class, and no existing class changes.

Changing behaviour at run time

Delegation means an object does part of its job by calling a method on another object it holds, like OrderNotifier handing each message to its channels.

A composed object can change its parts while the program runs. Below, Asha switches SMS off and then email off in her settings, and the same notifier follows.

Example 3 · Turning channels on and off while running

RuntimeChannelsDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Customer(String name, String email, String phone) {}
interface NotificationChannel {    void send(Customer c, String text);}
class EmailChannel implements NotificationChannel {    public void send(Customer c, String text) {        System.out.println("Email to " + c.email() + ": " + text);    }}
class SmsChannel implements NotificationChannel {    public void send(Customer c, String text) {        System.out.println("SMS to " + c.phone() + ": " + text);    }}
class OrderNotifier {    private final List<NotificationChannel> channels = new ArrayList<>();
    void turnOn(NotificationChannel channel) {        if (!channels.contains(channel)) channels.add(channel);    }
    void turnOff(NotificationChannel channel) {        channels.remove(channel);    }
    void send(Customer c, String text) {        if (channels.isEmpty()) {            System.out.println("(no channels on for " + c.name() + ")");            return;        }        for (NotificationChannel channel : channels) {            channel.send(c, text);        }    }}
public class RuntimeChannelsDemo {    public static void main(String[] args) {        Customer asha = new Customer("Asha", "asha@mail.com", "9876543210");        NotificationChannel email = new EmailChannel();        NotificationChannel sms = new SmsChannel();
        OrderNotifier notifier = new OrderNotifier();        notifier.turnOn(email);        notifier.turnOn(sms);        notifier.send(asha, "ORD-21 confirmed");
        System.out.println("-- Asha turns off SMS in settings --");        notifier.turnOff(sms);        notifier.send(asha, "ORD-21 shipped");
        System.out.println("-- Asha turns off email too --");        notifier.turnOff(email);        notifier.send(asha, "ORD-21 delivered");    }}
Output
Email to asha@mail.com: ORD-21 confirmed
SMS to 9876543210: ORD-21 confirmed
-- Asha turns off SMS in settings --
Email to asha@mail.com: ORD-21 shipped
-- Asha turns off email too --
(no channels on for Asha)

What this code does

  • The same notifier object behaves differently after turnOff(sms). With inheritance you would need a new object of a different class.
  • turnOff removes the exact channel object passed in, which is why main keeps email and sms in variables.

An object's class is fixed when it is created, so inheritance decides behaviour at compile time. With composition, notifier.turnOff(sms) just removes one channel from the list: no new object and no new class.

When inheritance is still right

A fragile base class is a parent class whose changes, or inner workings, silently break its subclasses because they depend on how the parent works inside.

Inheritance is still right for a true is-a with a stable parent. Below is a family of ShopLite exceptions that extends the JDK's RuntimeException.

Example 4 · A good use of inheritance: an exception family

InheritanceStillRightDemo.javaJava
// A true is-a family with a stable base class from the JDKclass ShopLiteException extends RuntimeException {    ShopLiteException(String message) {        super(message);    }}
class OutOfStockException extends ShopLiteException {    OutOfStockException(String product) {        super(product + " is out of stock");    }}
class PaymentFailedException extends ShopLiteException {    PaymentFailedException(String orderId) {        super("payment failed for " + orderId);    }}
public class InheritanceStillRightDemo {    static void placeOrder(String orderId, String product, int stock, boolean paymentOk) {        if (stock == 0) throw new OutOfStockException(product);        if (!paymentOk) throw new PaymentFailedException(orderId);        System.out.println(orderId + " placed");    }
    public static void main(String[] args) {        Runnable[] attempts = {            () -> placeOrder("ORD-31", "Earbuds", 5, true),            () -> placeOrder("ORD-32", "Smart watch", 0, true),            () -> placeOrder("ORD-33", "Hoodie", 3, false)        };        for (Runnable attempt : attempts) {            try {                attempt.run();            } catch (ShopLiteException e) {          // one catch for the whole family                System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());            }        }    }}
Output
ORD-31 placed
OutOfStockException: Smart watch is out of stock
PaymentFailedException: payment failed for ORD-33

What this code does

  • Every OutOfStockException really is a ShopLiteException, always, and the JDK base class is stable. That is the case inheritance was made for.
  • The single catch (ShopLiteException e) handles the whole family: the subtypes can stand in for the parent with no surprises.

"An OutOfStockException is a ShopLiteException" is true in every situation, and the parent is stable. Good signs: the child can be used wherever the parent is (LSP), the parent was designed to be extended, and you never swap the parent at run time.

Bad signs: you extend only to reuse a few methods, or you extend a class you do not own, such as ArrayList, to add a rule. That is how a fragile base class bites.

Find the bug

Spot the wrong inheritance

Click the line that should not use inheritance.

A cart must hold at most 3 items.

Round 1 of 2
Quick test: say "every X is a Y, always" aloud. If it sounds wrong in even one case, use composition.

How composition leads to patterns

Most patterns in this section are composition with a particular shape. Below, two of them appear in a few lines of ShopLite code.

Java
class LoggingChannel implements NotificationChannel {        // Decorator shape    private final NotificationChannel inner;    LoggingChannel(NotificationChannel inner) { this.inner = inner; }    public void send(Customer c, String text) {        System.out.println("log: " + text);        inner.send(c, text);    }}
class ChannelGroup implements NotificationChannel {          // Composite shape    private final List<NotificationChannel> members;    ChannelGroup(List<NotificationChannel> members) { this.members = members; }    public void send(Customer c, String text) { members.forEach(m -> m.send(c, text)); }}

Three shapes to recognise now, so later patterns feel familiar:

  • Strategy: hold one swappable behaviour, such as the PaymentMethod checkout uses.
  • Decorator: wrap an object of the same interface and add something before or after it.
  • Composite: a group that is itself one of the things it holds, such as a channel made of channels.

Next step

Check your understanding

10 quick questions