PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 20 ■ OBJECTS, PATTERNS, PRACTICE


copy of the Gang of Four book under their arm. They accost the uninitiated and reel off pattern names
like articles of faith. It is little wonder that some critics see design patterns as hype.
In languages such as Perl and PHP, patterns are also controversial because of their firm association
with object-oriented programming. In a context in which objects are a design decision and not a given,
associating oneself with design patterns amounts to a declaration of preference, not least because
patterns beget more patterns, and objects beget more objects.


What Patterns Buy Us


I introduced patterns in Chapter 7. Let’s reiterate some of the benefits that patterns can buy us.


Tried and Tested


First of all, as I’ve noted, patterns are proven solutions to particular problems. Drawing an analogy
between patterns and recipes is dangerous: recipes can be followed blindly, whereas patterns are “half-
baked” (Martin Fowler) by nature and need more thoughtful handling. Nevertheless, both recipes and
patterns share one important characteristic: they have been tried out and tested thoroughly before
inscription.


Patterns Suggest Other Patterns


Patterns have grooves and curves that fit one another. Certain patterns slot together with a satisfying
click. Solving a problem using a pattern will inevitably have ramifications. These consequences can
become the conditions that suggest complementary patterns. It is important, of course, to be careful
that you are addressing real needs and problems when you choose related patterns, and not just
building elegant but useless towers of interlocking code. It is tempting to build the programming
equivalent of an architectural folly.


A Common Vocabulary


Patterns are a means of developing a common vocabulary for describing problems and solutions.
Naming is important—it stands in for describing, and therefore lets us cover lots of ground very quickly.
Naming, of course, also obscures meaning for those who do not yet share the vocabulary, which is one
reason why patterns can be so infuriating at times.


Patterns Promote Design


As discussed in the next section, patterns can encourage good design when used properly. There is an
important caveat, of course. Patterns are not fairy dust.


Patterns and Principles of Design


Design patterns are, by their nature, concerned with good design. Used well, they can help you build
loosely coupled and flexible code. Pattern critics have a point, though, when they say that patterns can
be overused by the newly infected. Because pattern implementations form pretty and elegant structures,
it can be tempting to forget that good design always lies in fitness for purpose. Remember that patterns
exist to address problems.

Free download pdf