Quantcast
Channel: HauteLook Engineering Blog » Chris Hanson
Viewing all articles
Browse latest Browse all 10

Design Principle: Favor Composition Over Inheritance

$
0
0

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.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images