PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 6 ■ OBJECTS AND DESIGN


Conditional Statements


You will use if and switch statements with perfectly good reason throughout your projects. Sometimes,
though, such structures can be a cry for polymorphism.
If you find that you are testing for certain conditions frequently within a class, especially if you find
these tests mirrored across more than one method, this could be a sign that your one class should be two
or more. See whether the structure of the conditional code suggests responsibilities that could be
expressed in classes. The new classes should implement a shared abstract base class. The chances are
that you will then have to work out how to pass the right class to client code. I will cover some patterns
for creating objects in Chapter 9.


The UML


So far in this book, I have let the code speak for itself, and I have used short examples to illustrate
concepts such as inheritance and polymorphism.
This is useful because PHP is a common currency here: it’s a language we have in common, if you
have read this far. As our examples grow in size and complexity, though, using code alone to illustrate
the broad sweep of design becomes somewhat absurd. It is hard to see an overview in a few lines of code.
UML stands for Unified Modeling Language. The initials are correctly used with the definite article.
This isn’t just a unified modeling language, it is the Unified Modeling Language.
Perhaps this magisterial tone derives from the circumstances of the language’s forging. According to
Martin Fowler (UML Distilled, Addison-Wesley Professional, 1999), the UML emerged as a standard only
after long years of intellectual and bureaucratic sparring among the great and good of the object-
oriented design community.
The result of this struggle is a powerful graphical syntax for describing object-oriented systems. We
will only scratch the surface in this section, but you will soon find that a little UML (sorry, a little of the
UML) goes a long way.
Class diagrams in particular can describe structures and patterns so that their meaning shines
through. This luminous clarity is often harder to find in code fragments and bullet points.


Class Diagrams


Although class diagrams are only one aspect of the UML, they are perhaps the most ubiquitous. Because
they are particularly useful for describing object-oriented relationships, I will primarily use these in this
book.


Representing Classes


As you might expect, classes are the main constituents of class diagrams. A class is represented by a
named box, as in Figure 6–1.


Figure 6–1. A class

Free download pdf