Design Patterns with Missing Pieces

Why are Participants Missing? Note: Gentle reader, This article was written for our new PHP Design Pattern blog, but the points apply as well to ActionScript 3.0. As a result, I decided to include it here. The links in this post have been changed to go to the relevant ActionScript 3.0 posts, but otherwise, the article is the same. After writing design patterns in PHP for a while, I’ve come to appreciate the strongly typed structure of ActionScript 3.0. Programming to the interface in PHP is tricky, but possible. However, when you have strong typing as ActionScript 3.0 does, you really appreciate it more once you’ve worked with a dynamic language without strong data typing.

The Case of the Missing Participants

Recently I was working on a Decorator pattern and struggling through PHP’s way of doing things. So naturally I thought why not take a look at how others have solved these same problems. The Gang of Four refer to the different classes and interfaces that make up a design pattern, as participants, and when I look at a design pattern, the first thing I do is to see how the developer handles the different participants. What I found was surprising—they left out chunks of a design pattern in their examples. Alternatively, they just did some kind of workaround that effectively made it work (run), but it was no longer a design pattern or had the advantages of a design pattern.

The Strategy with the Missing Context

The Strategy pattern decouples the algorithms from the Client by using a Context class. All of the requests for the algorithms (found in concrete Strategy classes) go through the Context to the Strategy interface and on the the implemented strategies in the form of concrete classes. However, in many of the PHP examples, they leave out the Context class and Strategy interface and go directly from an Object to concrete Strategies. In several examples, the code authors chose to ignore the interfaces and even the abstract classes and have fairly direct connections between concrete strategies and some kind of object. Figure 1 shows the kinds of UMLs that accompany these kinds of PHP design pattern implementations—if indeed they are implementations.

Figure 1: Minimalist UML

You can see clearly that the UML in Figure 1 has little in common with the class diagram we used that was an exact replica of the Strategy pattern that the Gang of Four uses.

The authors of this kind of “explanation” of the Strategy pattern seem to think that the separation of the algorithms from the object is a matter of nothing more than taking the algorithms out of some object and using them independently of the main object. However, while that is an improvement on cramming everything into a single object (class), it is not a design pattern. Yes, it does add flexibility because more than one class can use the same concrete strategies. So, it’s a step away from single-class programming and even procedural programming. However, it is not a design pattern and it does not have the design pattern’s flexibility. The Context class uncouples the request from the strategy and without it, that concrete strategies are tightly linked to the “object”—whatever that may be.

The Decorator Without Abstractions

Every time I look at the Decorator’s class diagram, I shiver. It is the only design pattern with an abstract class that subclasses another abstract class. However, it does promote loose coupling and in its own way, an elegant design. In looking at every single implementation of the Decorator in PHP, something is missing. In one class diagram using the Unified Modeling Language (UML), not only did the author show only two participants (the main object) and the decorator object, but he shows the “decorator” implementing the main object.

Unlike ActionScript 3.0, PHP does have real abstract classes and functions. So you’d think it’d be easier to implement a pattern where one abstract class subclasses another. That may be the case, but in looking at Decorator patterns in PHP, I did not see this. (I may have missed it, and if so, please send a comment letting me know where I can find it.) Using ActionScript 3.0 without real abstract classes or functions, we were able to treat the Component and Decorator classes as abstract classes by not implementing them, but with abstract accessors (or visibility) you’d think it would not require as much though and work. Nevertheless, I’m still trying to find a PHP example showing the correct relationships between participants and without any missing in a Decorator.

For some reason, PHP programmers have adopted these abbreviated and inaccurate UMLs. My question is, Why? Why leave out participants that play key roles and just go on one’s merry way? They take the general idea and create something that lacks the structure that promotes loose coupling and then claim the results are design patterns. They’re not.

Where’s the Client?

One of the key elements in understanding design patterns is the role of the Client class. In many design patterns the Client is actually part of the design (e.g., Composite, Chain of Responsibility) or implied in the class diagram by a gray Client box with a specified relationship (e.g., Proxy, Iterator). The other design patterns that show no role in the class diagram for the Client are discussed in the GoF book. For example, the Strategy design pattern shows no role for the Client in the class diagram, but in discussing Strategy pattern collaborations, Gamma and his associates point out,

A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from. (p. 317)

However, rarely have I seen a PHP example where there’s a Client class identified as such. Do requests emanate from a mysterious object and like magic turn an application into a design pattern? No. Requests come from a Client class, and these clients are discussed in every design pattern by the Gang of Four. Further, the class diagram either needs to show in the UML where the entry point/s is/are or explain it clearly in the write-up or other documentation. So, if I see no role for a Client, I usually conclude that the author may not have it exactly right.

Getting the Idea Right and Getting the Implemented Pattern Right

In reading the advantages of design patterns by some of the PHP design patterns authors, I was certain that they knew what they were doing. They seemed to understand the concept of re-usability, composition, and even programming to an interface instead of to an implementation—beautifully executed using code-hinting (the closest thing PHP has to data typing.)

However, following up on the right idea is a program with pieces missing. An easy counter-claim is that I’m being a purist, but that’s like saying that if the answer to 5 + 5 is 11, a purist is one who demands that the answer be 10. (After all 11 is close to the right answer.) This is not about a one-solution answer. Rather, it’s about putting all of the pieces of the puzzle together before claiming completion.

Put Up or Shut Up

It is true that I have not read every book or article (online or in print) on PHP design patterns, but from what I’ve seen in the books and online articles, most leave something out. It’s not that PHP programmers lack the right stuff—they don’t. Rather, it seems that some of the early examples of PHP design patterns got it wrong and others went on to follow up these wrong examples. While I’ve seen wrong examples of design patterns for every other language, including ActionScript 3.0, Java, C# and C++, PHP seems to have more than it’s share.

The goal is not to show how smart we are. Rather, in discussing what needs to be a part of a design pattern I’ve found that I have to think through exactly why each participant in a design pattern has to be there. For example, in the Strategy pattern, why do we need the Context class? Why can’t the Client make a request directly to the strategies, even going through the Strategy interface? After all, the Context is a concrete class; thus, it’s not the interface that we’re after. Including all of the participants in a design pattern example requires that each participant’s role be explained. Those explanations should help us better understand what the pattern accomplish, and we can better understand design patterns. That is the goal of this blog.

So now we’re stuck with coming up with good examples and better explanations of what design patterns are supposed to accomplish for the PHP programmer. Naturally, after being so critical of PHP patterns, we need to hold ourselves to those same standards. Given the rapid evolution of PHP from PHP 4 to the verge of PHP 6, one might think that it’s better to wait until PHP 6 is officially the new standard. However, in looking at PHP 6, you’ll find that a good PHP 5 program cast in a design pattern is easy to update (as are all programs using design patterns.) On this blog we’ll put up examples with the expectation that we’ll be examined and corrected where we need to be. The goal is to explore the value design patterns in PHP and get it right in doing so.

4 Responses to “Design Patterns with Missing Pieces”


  • PHP developer world has just gained a great additional reinforcement. You made really good and reasoned critics – maybe a little a bit biased due to the purist factor – that everybody can think about it and improve.

    Keep on bloging Bill! =D

  • Hi William,

    Thanks for the kind words. I have always enjoyed PHP, and the PHP programmers I know truly love to program. One of the problems with a “dynamic language” is the ability to get things done without the added discipline required in strictly typed languages like ActionScript 3.0. Another way of putting it is that PHP is more forgiving than ActionScript 3.0. As a result, the emphasis is on good algorithms rather than on loose coupling in the program’s structure. I fear that many PHP programmers have been led to believe that “tight code” is a matter of using as few lines of code as possible and resolving issues with conditional structures rather than communication between objects.

    As a result, I probably seem more purist. I think that getting it right as far as what the Gang of Four had in mind requires a careful consideration of all of the participants in a design pattern. That’s why I wrote this post. The PHP examples simply used the general idea of a design pattern but missed the value of the pattern. For example, in a glowing and loving description of the Strategy pattern, one author gushed about what a great idea it is to separate the algorithms from an object. Then he shows the class diagram I did in Figure 1. Well, if you take all of the algorithms from an object, there’s nothing left of the object. If by “object” he means the Context class that takes care of delegation in conjunction with the Client, he has the UML arrow pointing the wrong way and the wrong symbol. (The relationship between the Context and Strategy interface is aggregation represented by a line from the Context to the Strategy with a diamond on the Context side.)

    I’m not one of those who shrieks,

    You will burn in hell if you do it wrong!

    Further, it’s really difficult to say to someone who advocates using design patterns that they are missing the point and doing it wrong. However, when you leave out participants in a design pattern it’s not going to work right. With friends like this, who needs enemies? Groan….

    Kindest regards,
    Bill

  • Whoa! What a big reply! You really like to talk about Design Patterns huh?! That’s good because I like it too! hahahaha.

    I think we share part of the same “feeling” when working with “dynamic languages”. I learned to program using strong typed structural languages (Pascal, C) which made my roots. When I first tried an OOP language (C++, Java) it was such a shock, paradigm breakdown. Finally, after lots of struggle with the concepts and techniques I find my self quite comfortable with it. Recently I’ve been trying to “evolve” and really learn how to use a dynamic language. But the thing is, to really accomplish this, is to embrace this new paradigm, different way of thinking and abstracting. Another paradigm break down! Quite hard for me but at the same time interesting.

    So that’s why I usually think that the general design patterns, in GoF’s book, are not very suited for dynamic languages. Okay, the IDEAS and GOALS are definitely agnostic of the programming language but the way they are implemented that is not suited. The implementations take advantage of the full power of OOP ( and some times of a language) so they work brilliant for strong typed languages.

    Summing up, the design patterns should be totally revised, re-thinked and re-implemented in order to port/adapt them to a different paradigm and take full advantage of dynamic languages. Or else, I feel it’s like using a wrong/not specific tool for solving a problem. Like trying to hammer a nail using butter.

    Cheers mate!

  • Hi William,

    It took Chandima and me a looooong time to get things straight with ActionScript 3.0 and design patterns. Most of my time spent with design patterns initially was with Java (which I rarely use) and C# (which I use occasionally), and I was often in a funk about ActionScript 3.0’s chances with design patterns because it lacked true abstract classes and methods. However, after much prodding and poking, we found ways to implement the design patterns, and while sometimes awkward, we were able to move forward.

    After going to OOPSLA meetings beginning in 2006, I was able to talk with the best and the brightest in object oriented programming. What struck me was that they too understood that design patterns were not easy—they had to teach these patterns to their students. You’d think that someone with a Ph.D. in computer science could easily understand and explain design patterns; they often struggled like we do.

    As far as dynamic languages and design patterns are concerned, I first ran into them at the OOPSLA meetings. These guys had written different design patterns in PHP (and even some in JavaScript). By the time I started re-visiting PHP, it was at PHP 5 (5.3.1 on my Mac), and they had introduced Type Hinting. The Type Hinting documentation (http://us.php.net/manual/en/language.oop5.typehinting.php) includes the point that it is quite helpful in programming to the interface instead of the classes (or implementations). Voila! Here’s the answer to the fundamental issue of

    program to the interface; not the implementation.

    Even so, in the same documentation, one contributor points out that the use of Type Hinting requires more processing time. That is true. However, we’re no longer using 8-bit processors and 64k worth of memory. Back in the day, I used to demonstrate the benefits of using Assembly/Machine language over BASIC. I wrote a loop through the display memory in BASIC, and you could watch as the loop trudged through the sequential addresses used for display. Then I’d demonstrate the exact same sequence created using Assembly language. It was instantaneous. The display changed in a blink of the eye. However, very few wanted to take the time it does to write all of the details required by Assembly language. (Or languages like FORTH for that matter.)

    The “More Cycle Time” argument eventually leads to micro-coding where one could argue that unless you code in 0’s and 1’s, you’re wasting processor time with the overhead demanded by languages—even machine language with all of the overhead required by opcodes. (A couple of bits or bytes…) I’m not saying that if you can shave a few cycles off an algorithm you shouldn’t. Rather, I’m saying that if programming to the interface adds a few cycles that no one can sense, you shouldn’t lose any sleep over it. What you need to lose sleep over is programming in a style that requires days, weeks, even months to re-write using objects that you cannot re-use.

    Here is the true value of design patterns. What you will lose in processing time is not noticeable to the user, especially with 32-64 bit processing. All of the costs for design patterns are up front. Learning how to use them is damn difficult! It’s not for everyone, and like nature the weak just won’t make it. However, the payoffs are huge when it comes time for 1) Change and 2) Re-use. As we all know, the most persistent element in programming sites is change. Change comes either as a built-in feature of a site or because the customer changes his/her mind—usually because the customer is trying to stay in business! If we ask ourselves, what’s easier, saving a few cycles in processor time that no one notices or spending time learning how to save a huge amount of time re-writing a program?

    Note: As a side-note, those clamoring about shaving a few cycles off here and there, willy-nilly use conditional statements like confetti in their programs, while ignoring the crispness of patterns like the Strategy and State that are free of conditionals!

    When it comes to dynamic languages like PHP, especially PHP 5+, I see no reason to change anything in what the Gang of Four presented . After all, we have been able to implement design patterns in ActionScript 3.0 even though they lack abstract classes. So while PHP 5+ does not have strict typing (outside of Type Hinting), it has abstract classes and methods. The advantages of using design patterns is just too great to ignore. Most businesses (including our own) just cannot afford the time and effort to revise programs that do not use design patterns. The same is true for PHP and other dynamic languages. It’s not going to be the “purity” of the design that encourages change; it will be the practical realities.

Leave a Reply