May 26, 2018
Hot Topics:

PHP Pattern Principles

  • October 13, 2005
  • By Matt Zandstra
  • Send Email »
  • More Articles »

Although design patterns simply describe solutions to problems, they tend to emphasize solutions that promote reusability and flexibility. To achieve this, they manifest some key object-oriented design principles.

This article will cover

  • Composition: How to use object aggregation to achieve greater flexibility than you could with inheritance alone
  • Decoupling: How to reduce dependency between elements in a system
  • The power of the interface: Patterns and polymorphism

The Pattern Revelation

I first started working in an object-oriented context using the Java language. As you might expect, it took a while before some concepts clicked. When it did happen, though, it happened very fast, almost with the force of revelation. The elegance of inheritance and encapsulation bowled me over. I could sense that this was a different way of defining and building systems. I “got” polymorphism, working with a type and switching implementations at runtime.

All the books on my desk at the time focused on language features and the very many APIs available to the Java programmer. Beyond a brief definition of polymorphism, there was little attempt to examine design strategies.

Language features alone do not engender object-oriented design. Although my projects fulfilled their functional requirements, the kind of design that inheritance, encapsulation, and polymorphism had seemed to offer continued to elude me.

My inheritance hierarchies grew wider and deeper as I attempted to build new classes for every eventuality. The structure of my systems made it hard to convey messages from one tier to another without giving intermediate classes too much awareness of their surroundings, binding them into the application and making them unusable in new contexts.

It wasn’t until I discovered Design Patterns, otherwise known as the Gang of Four book, that I realized I had missed an entire design dimension. By that time I had already discovered some of the core patterns for myself, but others contributed to a new way of thinking.

I discovered that I had overprivileged inheritance in my designs, trying to build too much functionality into my classes. But where else can functionality go in an object-oriented system?

I found the answer in composition. Software components can be defined at runtime by combining objects in flexible relationships. The Gang of Four boiled this down into a principle: “favor composition over inheritance.” The patterns described ways in which objects could be combined at runtime to achieve a level of flexibility impossible in an inheritance tree alone.

Composition and Inheritance

Inheritance is a powerful way of designing for changing circumstances or contexts. It can limit flexibility, however, especially when classes take on multiple responsibilities.

The Problem

As you know, child classes inherit the methods and properties of their parents (as long as they are protected or public elements). We use this fact to design child classes that provide specialized functionality. Figure 1 presents a simple example using the UML.

Figure 1: A parent class and two child classes

The abstract Lesson class in Figure 1 models a lesson in a college. It defines abstract cost() and chargeType() methods. The diagram shows two implementing classes, FixedPriceLesson and TimedPriceLesson, which provide distinct charging mechanisms for lessons.

Using this inheritance scheme, we can switch between lesson implementations. Client code will know only that it is dealing with a Lesson object, so the details of costing will be transparent.

What happens, though, if we introduce a new set of specializations? We need to handle lectures and seminars. Because these organize enrollment and lesson notes in different ways, they require separate classes. So now we have two forces that operate upon our design. We need to handle pricing strategies and separate lectures and seminars. Figure 2 shows a brute-force solution.

Figure 2: A poor inheritance structure

Figure 2 shows a hierarchy that is clearly faulty. We can no longer use the inheritance tree to manage our pricing mechanisms without duplicating great swathes of functionality. The pricing strategies are mirrored across the Lecture and Seminar class families. At this stage, we might consider using conditional statements in the Lesson super class, removing those unfortunate duplications. Essentially, we remove the pricing logic from the inheritance tree altogether, moving it up into the super class. This is the reverse of the usual refactoring where we replace a conditional with polymorphism. Here is an amended Lesson class:

abstract class Lesson {
protected $duration;
const FIXED = 1;
const TIMED = 2;
private $costtype;
function __construct( $duration, $costtype=1 ) {
$this->duration = $duration;
$this->costtype = $costtype;
function cost() {
switch ( $this->costtype ) {
CASE self::TIMED :
return (5 * $this->duration);
CASE self::FIXED :
return 30;
$this->costtype = self::FIXED;
return 30;
function chargeType() {
switch ( $this->costtype ) {
CASE self::TIMED :
return "hourly rate";
CASE self::FIXED :
return "fixed rate";
$this->costtype = self::FIXED;
return "fixed rate";
// more lesson methods...
class Lecture extends Lesson {
// Lecture-specific implementations ...
class Seminar extends Lesson {
// Seminar-specific implementations ...

You can see the new class diagram in Figure 3.

Figure 3: Inheritance hierarchy improved by removing cost calculations from subclasses

We have made the class structure much more manageable, but at a cost. Using conditionals in this code is a retrograde step. Usually, we would try to replace a conditional statement with polymorphism. Here we have done the opposite. As you can see, this has forced us to duplicate the conditional statement across the chargeType() and cost() methods.

We seem doomed to duplicate code.

Page 1 of 4

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date