Design Principle: Favor Composition Over Inheritance

Here at HauteLook, we’re almost constantly interviewing engineers. Not because we have high turnover, but because we’re always growing the team and it’s difficult to find engineers that have the skill level required to join our team. Part of our interview includes a “virtual whiteboard” using a Google doc. And part of that virtual whiteboard exercise includes representing a complex object, showing its properties and methods. We don’t ask for (or care about) valid UML; all that we care about is seeing that the candidate understands object-oriented design (OOD).

Many of our candidates do a wonderful job of constructing a complex hierarchy of inheritance. This gets the job done, but it doesn’t really allow a system to be extensible. When you overuse inheritance, you are basically designing according to assumptions which may seem true at the time, but which will likely not be true as the application is required to change. A key design principle is Encapsulate What Varies. The design principle covered in the post you’re currently reading, Favor Composition Over Inheritance, is one way of following the Encapsulate What Varies principle.

The overuse of inheritance in OOD is common, and is understandable. Many code examples in textbooks show inheritance as the way to make code reusable. And a design that utilizes a nice inheritance hierarchy does appear to make good sense. However, when you need to make a system do something that you hadn’t originally designed it for, the benefits you thought you were getting from an inheritance hierarchy suddenly become the sole reason to refactor your code. When subclasses inherit multiple behaviors from a parent class, they are locked into having those behaviors. The solution is simple, right? Just override those methods and implement the desired behavior for that subclass. But what if another subclass of the same parent has the same issue? Now, if you override the behavior in that subclass too, you have duplicated code.

Let me provide an example. (Note that I’m not going to design classes as we ask for in our whiteboard exercise. Instead, I’ll demonstrate this principle with code.) Let’s say that we want to design a class that plays music. The two concrete examples that we are required to implement are a record player (to play all the awesome 70’s music) and an 8-track player (just because). So we design a base AbstractPlayer class. It might look something like this:

abstract class AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through my speakers!";
    }

    public function stop()
    {
        echo "I'm not playing music anymore.";
    }
}

Looks simple enough, right? And our RecordPlayer and EightTrackPlayer classes would inherit from AbstractPlayer and would therefore inherit the play() and stop() methods:

class RecordPlayer extends AbstractPlayer
{

}

class EightTrackPlayer extends AbstractPlayer
{

}

Here’s some client code using the RecordPlayer:

$record_player = new RecordPlayer;
$record_player->play(); // echoes "I'm playing music through my speakers!"

Awesome! So now, some time goes by, and we get a request to implement a portable cassette player. It would probably be just like the above two concrete classes, but it would need to be able to play through headphones instead of speakers. Here’s what it might look like:

class PortableCassettePlayer extends AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

Makes sense, right? Our PortableCassettePlayer inherits from AbstractPlayer and tweaks the play() method a little. Now, fast-forward a couple of decades, and we need to implement an Mp3Player class.

class Mp3Player extends AbstractPlayer
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

Notice that we essentially copied the play() method from the PortableCassettePlayer class. We couldn’t just use the play() method from the base class because the Mp3Player can have headphones plugged in. Maybe we could inherit from the PortableCassettePlayer class, but then we’d inherit a ton of other functionality, such as ejecting a cassette tape, which doesn’t make sense for an MP3 player. The problem here is that inheritance has locked us into certain assumptions, and the design that was intended to encourage code reuse actually causes code duplication.

Instead of using inheritance to reuse functionality, let’s look at a design that uses composition. First, we’ll encapsulate the play() behavior:

interface PlayBehaviorInterface
{
    public function play();
}

class PlayBehaviorSpeakers implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music through my speakers!";
    }
}

class PlayBehaviorHeadphones implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music through headphones!";
    }
}

Now the play functionality is encapsulated into classes. Maybe you’re thinking, “aren’t classes supposed to represent things?” Well, in this case, the thing they’re representing is a behavior.

Let’s see how the Player classes can now use these new behavior classes.

abstract class AbstractPlayer
{
    protected $play_behavior;

    abstract protected function _createPlayBehavior();

    public function __construct()
    {
        $this->setPlayBehavior($this->_createPlayBehavior());
    }

    public function play()
    {
        $this->play_behavior->play();
    }

    public function setPlayBehavior(PlayBehaviorInterface $play_behavior)
    {
        $this->play_behavior = $play_behavior;
    }

    public function stop()
    {
        echo "I'm not playing music anymore.";
    }
}

Notice that the AbstractPlayer has a constructor which sets the default player behavior. It also has a new setPlayBehavior() method. This allows to set whatever play behavior we want at runtime. It also requires implementation of a method called _createPlayBehavior(), so concrete classes are forced to provide their default player behavior. (see my post on Removing Dependencies With Factory Method.)

Let’s create our Mp3Player class:

class Mp3Player extends AbstractPlayer
{
    protected function _createPlayBehavior()
    {
        return new PlayBehaviorHeadphones;
    }
}

The Mp3Player class sets an instance of PlayBehaviorHeadphones as its play behavior. Pretty cool, right? So imagine that a few more years pass, and now our Mp3Player needs to also support playing through a Bluetooth connection. What do we need to change in our Mp3Player class? Think about it for a second. The answer: absolutely nothing! We simply write a new class to encapsulate this new behavior:

class PlayBehaviorBluetooth implements PlayBehaviorInterface
{
    public function play()
    {
        echo "I'm playing music wirelessly through Bluetooth!";
    }
}

This new behavior class can be plugged into the Mp3Player class at runtime if the player is meant to support this functionality. The client code that instantiates the Mp3Player class handles this:

$mp3_player = new Mp3Player;
$mp3_player->play(); //echoes "I'm playing music through headphones!"
$mp3_player->setPlayBehavior(new PlayBehaviorBluetooth);
$mp3_player->play(); //echoes "I'm playing music wirelessly through Bluetooth!"

Beautiful, right? Encapsulating behaviors into separate classes gives us true extensibility. In fact, design principles such as Favor Composition Over Inheritance are the reason that we have design patterns. The main pattern used in the above examples is Strategy Pattern. Some other patterns that demonstrate this principle are Observer, Decorator, and State.

Oh, and one more thing to mention: the fact that we were able to drop in new functionality without changing existing code exemplifies another awesome design principle, the Open-Closed Principle. This principle states that classes should be closed to modification but open to extension.

As you think about how to structure your code, I encourage you to keep this principle in mind, and see how it can improve your design. You’ll thank yourself when you have to go back and add new functionality.

6 Responses to “Design Principle: Favor Composition Over Inheritance”

  1. Dharmesh October 9, 2013 at 7:19 AM #

    well done. Explanation is clear and without noise.

  2. vikhyath November 6, 2013 at 4:59 AM #

    Simple and easy to understand. Good article.

  3. gary mort November 19, 2013 at 12:47 AM #

    This type of code makes things harder to read and understand, in favor of making them more flexible to change. In the long run, whether or not the steeper learning curve is worth the flexibility is a matter of taste. Note: not the learning curve of the concept, the concept alone is useless without a discipline of coding style. In this case, the style is AbstractTyper contains method createTypeBehavior and property type_behavior. So as long as everything can be broken up neatly into a Type which can also has some sort of instantation name such as Typer – all is good.

    Since PHP 5.4 adds Traits to it’s bag of tricks, http://php.net/manual/en/language.oop5.traits.php all of those different options could have been designed into a single PlayFromHeadphones trait and reused without having to come up with cool sounding method names/styles.

    Not that there is any problem with using cool features to have fun..maximizing fun in coding maximizes productivity – just don’t confuse taste with technical superiority.

  4. Amit Lamba January 14, 2014 at 12:26 PM #

    Excellent post about the principle of favoring composition over inheritance. You made it very easy to grasp. Now I just need to wrap my brain around design patterns (Strategy and Factory, specifically) to fully digest how you refactored the code (your thought process).

    It’s one thing to understand a concept, it’s another to recognize a situation where you can utilize a design pattern.

  5. rdp February 14, 2014 at 11:16 AM #

    Thanks! Best explanation i’ve seen about composition vs inheritance.

Trackbacks/Pingbacks:

  1. Entity component system : Component tips | Box Hacker - September 14, 2013

    […] entity framework is based on composition over inheritance which means each component is solely purposeful and should never have behavior overwritten, because […]

Leave a Reply:

Gravatar Image