Archive for the 'Design Patterns Principles' Category

Page 2 of 2

OOP Principles: The Liskov Substitution Principle

liskovPrinciples Rule!
It’s been a while since OOP/Design Pattern principles have been a topic on this blog, and now is as good time as any. The 1987 OOPSLA keynote address by Barbara Liskov contained what has become known as the Liskov Substitution Principle. In that address and books and papers, the Liskov principle is an OOP one that is part of the more general OOP set of principles. In languages like C++ and Java where you have strongly typed languages, you can declare a variable (property) by the parent data type. Since PHP is flexibly typed, the data type can change, and while that practice [changing data types for a variable] is not recommended, it is certainly possible. As a result, it’s not as easy to explain and illustrate the principle with PHP.

Essentially, the principle holds that,

If a Client is using a reference to a base class it should be able to substitute a derived class for it without affecting the program’s operation

Actually Dr. Liskov said,:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

and I was trying to put it in less technical terms.

Why is the Liskov Substitution Principle Important?

You can easily see three reasons that the principle is important:

  1. If substitutions cannot be made then class hierarchies would be a mess. Whenever a subclass instance is passed as parameter to any method, surprises might occur.
  2. Without the possibility of Liskov type substitutions unit tests for the superclass would never succeed for the subclass.
  3. Changes are easier and more predictable because you know what to expect from the superclass.

No doubt you can find more, but for now, the Liskov substitution principle is another way to keep your code loose and reusable and subject to change.

If the Client has an object of a certain type, it should be able to substitute a derived object of the same type. For example, suppose you have an abstract class named Automobile and from that class you have subclasses of Ford, Toyota, and Peugeot. Your Client has an object, $myAuto. The $myAuto object can be any of the subclasses, and if a substitution is made for any one of them everything keeps on working without a problem and the change is unknown to the Client class. So if you substitute a Ford for a Toyota, the Client can work with the objects without having to adjust for the change. What’s more, if you want to add a Fiat or Mercedes Benz class as a subclass of Automobile, the $myAuto object handles it with nary a whimper.

The one caveat is that the subclasses must all honor the contractual conditions of the parent class. So, any methods in the parent class must be functioning in the subclass (aka, derived class.)

Now you may be thinking, So what? If you’re at all familiar with other principles of OOP and Design Patterns, this principle may sound vaguely familiar, but what is the importance of this concept/principle/idea? It is this: Because the Client is unaware of the concrete class that the object may implement, the structure is far more resilient. Not only can the same structure be reused, it can be changed, updated and generally fiddled with without easily breaking anything. (Think of adding more car manufacturers to the Automobile class.) As far as the Client is concerned, as long as the interface rules are followed with the object, everything is hunky-dory. To get started Play the example and Download the source code:
PlayDownload

A Simple Practice for PHP Programmers

As a principle, the Liskov Substitution Principle is easy to use. The problem is in demonstrating it in PHP because of the lack of assigned data types to properties. However, using PHP type hinting, you will see how it works using at a classic example where the Liskov substitution principle (LSP) is used.

Explanations of how LSP works often use a rectangle/square example. Typically most programmers see two alternatives to illustrate LSP programming a rectangle and a square; with LSP and without LSP.

Beginning with the geometric observation, all squares are also rectangles, we’re likely to create a structure like that shown in Figure 1:

Figure 1: Square is a child of Rectangle

Figure 1: Square is a child of Rectangle

After all, we can envision a square as nothing more than a rectangle with equal sides. So an operation such as,

makeRectangle(w,h);

is an effective way to make either a square or rectangle. We add the Square class simply to examine the LS Principle; otherwise creating rectangles or squares would be accomplished using the makeRectangle(w,h) method making sure that w and h are equal when making squares. The inheritance path clearly indicates that a Square object IS A Rectangle. (That is, the two have an IS A relationship.) However, because Rectangle is a concrete class if I substitute Rectangle for Square, I’m going to have to change the type. I cannot substitute an instance of Rectangle for an instance of Square. This violates the Liskov Substitution Principle.
Continue reading ‘OOP Principles: The Liskov Substitution Principle’

The Composite Design Pattern in PHP: Part III Getting Child Elements and Removing Composites and Leaves

removeGet the Children and Remove Them

If you haven’t looked at Part I and Part II of the Composite pattern series, you may want to do so first before looking at this post. As you saw in Parts I & II, the Composite pattern, while clearly working with a tree-like hierarchy is a great pattern that favors composition over inheritance, and as you work with this pattern, you’ll see why programming to the interface instead of programming to the implementation makes life easier for the programmer.

In this installment, I want to implement two key methods, getChild() and remove(). Going back to the beginning, again I’d like to use materials developed by former colleague and friend, Dr. Chandima Cumaranatunge. Also, I’m going to switch the main interface (IComponent) to an abstract class so that some of the methods can be implemented in the interface. Because both abstract classes and interfaces are both interfaces, the abstract class retains the name IComponent. To see all of the changes and the new implementations, first take a look at the outcome generated (click the Play button) and download the source code:
PlayDownload

Reference to Composites as Root Children

Up to this point, the Composite examples have worked perfectly well without implementing the getChild() method. All access to the composites and leaves has been handled by the operation() method. Why bother? First of all, the Client can directly access any single node. The child the program is “getting” is either a composite or a leaf, and there will be no need to iterate through the entire root component to find a single node. Secondly, and more importantly, the Client can create new nodes without creating new variables. When a node is removed, this insures good garbage collection. (Garbage collection, in this context, refers to regaining unused resources and memory used by the nodes that have been removed.) It makes for cleaner and faster operations.

Since the getChild() is part of the interface, first take a look at the abstract class. Then, we’ll look at the implementation in the Composite class.

< ?php
abstract class IComponent
{
    protected $parentNode;
 
    abstract function operation();
    abstract function add(IComponent $comOn);
    abstract function remove(IComponent $comGone);
    abstract function getChild($int);
    protected abstract function getComposite();
 
    protected function setParent(IComponent $compositeNode)
    {
        $this->parentNode=$compositeNode;
    }
 
    public function getParent()
    {
        return $this->parentNode;
    }
 
    protected function removeParentRef()
    {
        $this->parentNode=null;
    }
}
?>

As you can see, the getChild($int) method is still abstract with a single parameter. Were it possible in PHP, an int type-hint would be included in the parameter; so we’ll just have to make-do with the variable name, $int to assure that we remember to use an integer in the parameter. However, the method’s implementation is pretty straightforward:

public function getChild($int)
{
   if(($int > 0) && ($int < = count($this->aChildren)))
    {
        return $this->aChildren[$int-1];
     }
     else
     {
         return null;
     }   
}

The method checks the value of the integer to make sure it’s greater than zero and greater than or equal to the length of the array (aChildren) and then returns the requested object as an element of the array. Otherwise, it returns a null value.

The value of the method becomes apparent in the Client reference, as the following snippet from the Client shows:

...
$this->rootCompos=new Composite("Root");       
$this->rootCompos->add(new Composite("-Composite 1"));
$this->rootCompos->getChild(1)->add(new Leaf("--C1:leaf 1"));
...

On the third line of the snippet, the leaf is added to the first child (a Composite instance) instead of to a variable holding the reference to the first child. As you will see, this approach requires no new variable for the composite name.

Safe Removal

In an earlier version of a Composite design I had made, I used something like the following to implement the remove() method:

function remove(IComponent $node)
{
    $nodeNow = array_search($node, $this->aChildren);
    unset($this->aChildren[$nodeNow]);
}

That works fine, but to my surprise, I found that others considered it “unsafe.” Specifically, the Freemens (Head First Design Patterns p367) noted that a Client might inadvertently try to add a composite element to a leaf node.
Continue reading ‘The Composite Design Pattern in PHP: Part III Getting Child Elements and Removing Composites and Leaves’

The Composite Design Pattern in PHP: Part II Composing with Images

cornerDon’t forget to Program to the Interface!

While the primary principle we draw from the Composite pattern is , Favor object composition over class inheritance, as discussed in Part I of the Composite series, another important principle applies here as well. The very first principle of design patterns is, Program to an interface, not an implementation. In a sense this is saying, program to an abstract parent and not a concrete child, but if you understand an interface to be the structure implied in either an interface (as used in the first and in this example) or an abstract class, you can see what the value of that principle is.

In this part, instead of a single leaf and a hierarchy rending output, this example shows how a Composite design with multiple leaves can be used to create a mosaic—which is the essence of composite! The interface (IComponent) is little changed except the string parameter has been removed from the operation() method and replaced (for clarity) with a method named showPix() with no parameters. All of the other methods remain the same. Play the application and download the source code and files to get started:
PlayDownload

Follow the Structure; Not the Sequence

To get out of the tar pit of sequential programming, look at the structure and think in terms of using larger structural concepts. Take a look at the three key participants in the Composite pattern, beginning with the key structural participant, the IComponent interface, focusing on their structure as outlined in the interface.


//IComponent.php
interface IComponent
{
    public function showPix();
    public function add(IComponent $comOn);
    public function remove(IComponent $comGone);
    public function getChild($someInt);
}
?>

As in Part I, the IComponent has four methods to be implemented, and though all four are implemented, only the first two are used for this second part. The focus is still on the idea of composition. The fact that we don’t need the second two right now does not detract from the fact that they (remove() and getChild() methods) unimportant for the pattern; just not for this example.

So the implementation of the the Composite class looks structurally similar to that in Part I, but the constructor function has no node name to identify in a parameter. Likewise, the showPix() method is almost identical to the operation() method in Part I, and only the name of the array has changed from $aChildren to $mosaic. Also, the echo statement is no longer part of the method.


//Composite.php
class Composite implements IComponent
{
    private $mosaic;
 
    public function __construct()
    { 
        $this->mosaic=array();
    }
 
    public function add(IComponent $comOn)
    {
        array_push($this->mosaic,$comOn);
    }
 
    public function remove(IComponent $comGone)
    {
        //Code to remove component
    }
 
    public function getChild($someInt)
    {
        //Code to get child by element value
    }
 
    //Note: The following method is recursive
    public function showPix()
    {
        foreach($this->mosaic as $tile)
        {
            $tile->showPix();
        }
    }
}
?>

If you’ve played both Part I and Part II examples of Composite patterns, you know they are very different in what they generate, but the structures for both are virtually identical. Each is combining leaf elements into composite ones. Same structure; different outcomes. That virtually defines code re-use.

Parts is Parts

While the implementation of the Composite class is little unchanged, the number and implementation of the leaf nodes are different. Each leaf class has a single task and no constructor parameter. The unused methods are implemented the same. Each leaf contains an HTML tag to an image. The Composite class stores instances of leaf instances in the $mosaic array and creates rows of images that are aligned to display the tiled image. You can think of each tile in the display as a leaf, and each row a composite of tiles and the entire mosaic as a composite of the three composites that make up the rows.


class Leafr1c1 implements IComponent
{   
    /* None of this batch of methods are used by leaf participants */
    /* However in order to correctly implement the interface */
    /* you need some kind of implementation */
    public function add(IComponent $comOn){}
    public function remove(IComponent $comGone){}
    public function getChild($someInt){}
 
    /* Display tile */
    public function showPix()
    {
        echo "r1c1";
    }
}
?>

Each of the leaf classes is named after a column and row where the tile is to be placed. For example the leaf class to place an image in Row 2, Column 3 of the mosaic is named Leafr2c3. Likewise, the names of the PNG graphic files share the same naming conviction. So Leafr2c3 has the code to display the r2c3.png image file.

The Client

As an integral part of the Composite design pattern, the Client can be seen as the artist who composes the mosaic. He does this by selecting each tile for the rows and arranges them to get the desired picture. Because no string parameter is in the leaf constructors, each leaf added to a composition does not need a name. (In a sense, the title names have been embedded into the leaf names.) The $bigPictue property is the same name as used in the original Client example, except this time, it really will produce a “big picture.” It is the root composition made up of three row compositions that are made up of three leaf elements.


ERROR_REPORTING( E_ALL | E_STRICT );
ini_set("display_errors", 1);
function __autoload($class_name) 
{
    include $class_name . '.php';
}
class Client
{
    private $bigPicture;
 
    public function __construct()
    {
        $this->bigPicture = new Composite();
        $row1=new Composite();
        $row1->add(new Leafr1c1());
        $row1->add(new Leafr1c2());
        $row1->add(new Leafr1c3());
        $this->bigPicture->add($row1);
 
        $row2=new Composite();
        $row2->add(new Leafr2c1());
        $row2->add(new Leafr2c2());
        $row2->add(new Leafr2c3());
        $this->bigPicture->add($row2);
 
        $row3=new Composite();
        $row3->add(new Leafr3c1());
        $row3->add(new Leafr3c2());
        $row3->add(new Leafr3c3());
        $this->bigPicture->add($row3);
 
        //Create a compostion
        echo "";
        echo "";
        echo "";
        echo "

Leaders in Composition

"
; echo "
India
"
;   $this->bigPicture->showPix();   echo "
Mahatma Gandhi
"
; echo ""; } } $worker=new Client(); ?>

In this installment, the goal is to show that the Composite design pattern is more than a tree-like hierarchy-making pattern. It is the essence of composition and the Composite design pattern. The mosaic image is a metaphor for the pattern in that it is composed of several compositions and elements within those compositions.

Adding the Final Touches

With two unimplemented methods (remove() and getChild()), in Part III of this series, you will see how they can be used for added flexibility with the Composite design pattern. I’d like to look at the original Gang of Four idea of using the Composite pattern to create a drawing program. Until next time, I welcome any and all comments.

The Composite Design Pattern in PHP: Part I from Conceptual to Practical

compositionShow Me the Practical!

A defining characteristic of PHP programmers is their practicality. Ironically, because of their practical orientation, they sometimes overlook the practicality of the abstract and conceptual. Focusing too much on a single (albeit quite useful and practical) implementation is like focusing on a single pixel in a graphic image—you can only see the pixel and miss the larger picture. That’s because the focus is in the wrong place. If you want to see the whole picture (the whole pattern and its parts), the individual pixels are not very practical, even though they are the atomic matter in computer graphics. In other posts on this blog, I have stressed the importance of having a complete design pattern with all of the participants a given design pattern is designed to include and provided a look-up table to check the parts list of all of the core patterns the Gang of Four developed. So in selecting an example to launch a discussion of the Composite pattern, I wanted an example with all of its parts. You can download the files and play a sample using the following two buttons:
PlayDownload

However, too much of a love affair with the conceptual and abstract is equally problematic. If you cannot use a pattern to get something accomplished, why waste time with it? Ironically, design patterns were developed solely for practical purposes, but in order to accomplish those practical goals, they had to provide a set of patterns that would be useful for a wide range of certain recurring programming problems. With these concepts in mind, this post begins with a conceptual example to see how the pattern works and then follow it up with a simple more practical example.

Overview

First things first. The class diagram for the Composite design pattern is both very simple, but it hides a real beauty and subtle complexity. Figure 1 shows the basic pattern:

Figure 1: Composite Design Pattern class diagram

Figure 1: Composite Design Pattern class diagram

Before going too far with an example, even an abstract one, consider the simplicity and irony of the pattern. First of all, the Composite implementation of the Component interface looks fairly cut and dried. However, the Leaf participant also implements the interface, but it doesn’t implement all of the abstract methods. It only implements the operation(). So maybe the interface is an abstract class? It doesn’t matter in PHP. If all of the abstract methods of a class that inherits an abstract class are not implemented, you get the following error:

Fatal error: Class Leaf contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

Since you can only declare an abstract method within an abstract class, you really have no choice but to implement it. Likewise with an interface all methods must be implemented; so with this first abstract example, I decided to use an interface instead of an abstract class.

Favoring Composition: A Tattoo for Your Spouse

One of the fundamental principles of design patterns is,

Favor object composition over class inheritance.

Figure 3: Tats for PHP Developers

Figure 3: Tats for PHP Developers

I tried to get my wife to get a tattoo with that piece of wisdom, but she balked at the idea. (I have no idea why; it’d be cool.) If any pattern adheres to that dictum, it’s the Composite pattern. The Composite participants are made up of Leaf primitives. So you can think of Composite implementations as compositions. The Leaf participants have no children. Think of the Leaf participants as parts that can be employed to create Composite participants.

For the longest time, that simple yet fundamental idea eluded me. In part, this was due to the Gang of Four’s intent statement that the pattern was to Compose objets into tree structures to represent part-whole hierarchies. I was too focused on the concept of hierarchy and not enough on compose to really appreciate the importance of the Composite design pattern.

So here, the first thing to do is to realize that the hierarchy is a form of composition. Imagine an automobile assembly plant where you have lots of parts, yet with those parts you can assemble different models of cars. You just have to use different selections of parts to compose the different models. The fact that the parts have a hierarchic arrangement is for efficiency; not the final product itself. Figure two shows what we hope to create in this initial implementation:

Figure 2: Different Compositions from Leaf Selections

Figure 2: Different Compositions from Leaf Selections


Continue reading ‘The Composite Design Pattern in PHP: Part I from Conceptual to Practical’