This chapter looks at what a pattern is; what it means to be patterns happy; the importance of understanding that patterns can be implemented in many ways; considerations for refactoring to, towards, or away from patterns; whether or not patterns make code more complex; what it means to have “pattern knowledge”; and when it may make sense to do up-front design with patterns.

What Is a Pattern?

Christopher Alexander, an architect, professor, and social commentator, inspired the software patterns movement with two literary masterpieces, A Timeless Way of Building [ Alexander, TWB ] and A Pattern Language [ Alexander, PL ]. Beginning in the late 1980s, software practitioners with years of experience began studying Alexander’s works and sharing their knowledge in the form of patterns and intricate networks of patterns, known as pattern languages . This led to the publication of valuable papers and books about patterns and pattern languages in such areas as object-oriented design, analysis and domain design, process and organizational design, and user interface design.

Pattern authors have often debated how to define a pattern, and many of the disagreements stem from how close to or far from Alexander’s view the debaters are. As I’m partial to Alexander’s view, I’ll quote him directly:

Each pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution.

As an element in the world, each pattern is a relationship between a certain context, a certain system of forces which occurs repeatedly in that context, and a certain spatial configuration which allows these forces to resolve themselves.

As an element of language, a pattern is an instruction, which shows how this spatial configuration can be used, over and over again, to resolve the given system of forces, wherever the context makes it relevant.

The pattern is, in short, at the same time a thing, which happens in the world, and the rule which tells us how to create that thing, and when we must create it. It is both a process and a thing; both a description of a thing which is alive, and a description of the process which will generate that thing. [ Alexander, TWB , 247]

Our industry’s view of patterns has mostly been influenced by catalogs of individual patterns, such as those found in Design Patterns [ DP ] and Martin Fowler’s Patterns of Enterprise Application Architectures [ Fowler, PEAA ]. Such catalogs don’t actually contain stand-alone patterns because authors typically discuss which alternative patterns to consider if a pattern doesn’t provide a good fit. In recent years, we’ve also seen the emergence of literature that resembles Alexander’s pattern languages. Such works include Extreme Programming Explained [ Beck, XP ], Domain-Driven Design [ Evans ], and Checks: A Pattern Language of Information Integrity [ Cunningham ].

Patterns Happy

On the back cover of Contributing to Eclipse [ Gamma and Beck ], a brief biography of Erich Gamma says, “Erich Gamma shared his joy in the order and beauty of software design as coauthor of the classic Design Patterns .” If you’ve ever produced or encountered an excellent design using patterns, you know this joy.

On the other hand, if you’ve ever produced or encountered patterns-dense code that is poorly designed because it doesn’t require the flexibility or sophistication of patterns, you know the dread of patterns.

The overuse of patterns tends to result from being patterns happy. We are patterns happy when we become so enamored of patterns that we simply must use them in our code. A patterns-happy programmer may work hard to use patterns on a system just to get the experience of implementing them or maybe to gain a reputation for writing really good, complex code.

A programmer named Jason Tiscioni, writing on SlashDot (see http://developers.slashdot.org/comments.pl?sid=33602&cid=3636102 ), perfectly caricatured patterns-happy code with the following version of Hello World.

interface MessageStrategy {
   public void sendMessage();
}

abstract class AbstractStrategyFactory {
   public abstract MessageStrategy createStrategy(MessageBody mb);
}

class MessageBody {
   Object payload;
   public Object getPayload() {
      return payload;
   }
   public void configure(Object obj) {
      payload = obj;
   }
   public void send(MessageStrategy ms) {
      ms.sendMessage();
   }
}

class DefaultFactory extends AbstractStrategyFactory {
   private DefaultFactory() {
   }
   static DefaultFactory instance;
   public static AbstractStrategyFactory getInstance() {
      if (instance == null)
         instance = new DefaultFactory();
      return instance;
   }

   public MessageStrategy createStrategy(final MessageBody mb) {
      return new MessageStrategy() {
         MessageBody body = mb;
         public void sendMessage() {
            Object obj = body.getPayload();
            System.out.println(obj);
         }
      };
   }
}

public class HelloWorld {
   public static void main(String[] args) {
      MessageBody mb = new MessageBody();
      mb.configure("Hello World!");
      AbstractStrategyFactory asf = DefaultFactory.getInstance();
      MessageStrategy strategy = asf.createStrategy(mb);
      mb.send(strategy);
   }
}

Have you ever seen code that resembles Jason’s Hello World program? I certainly have, on too many occasions.

The patterns-happy malady isn’t limited to beginner programmers. Intermediate and advanced programmers fall prey to it too, particularly after they read sophisticated patterns books or articles. For example, I discovered an implementation of the Closure pattern on a system I was helping to develop. It turned out that a programmer on the project had just learned the Closure pattern by studying it on the Wiki Web ( http://c2.com/cgi/wiki?UseClosuresNotEnumerations ).

As I studied this Closure implementation, I could not find a good justification for using it. The Closure pattern just wasn’t necessary. So I refactored the Closure pattern out of the code and replaced it with simpler code. When I finished, I asked the programmers on the team if they thought the newer code was simpler than the Closure code. They said yes. Eventually the author of the code also acknowledged that the refactored code was simpler.

It is perhaps impossible to avoid being patterns happy on the road to learning patterns. In fact, most of us learn by making mistakes. I’ve been patterns happy on more than one occasion.

The true joy of patterns comes from using them wisely. Refactoring helps us do that by focusing our attention on removing duplication, simplifying code, and making code communicate its intention. When patterns evolve into a system by means of refactoring, there is less chance of over-engineering with patterns. The better you get at refactoring, the more chance you’ll have to find the joy of patterns.

There Are Many Ways to Implement a Pattern

Every pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice. [ Alexander, PL , x]

Every pattern in the classic book Design Patterns [ DP ] contains a Structure diagram. For example, the Structure diagram for the Factory Method pattern looks like this:

There Are Many Ways to Implement a Pattern

This diagram indicates that the Creator and Product classes are abstract, while the ConcreteCreator and ConcreteProduct classes are concrete. Is this the only way to implement the Factory Method pattern? By no means!

In fact, the authors of Design Patterns go to great pains to explain different ways to implement each pattern in a section called Implementation Notes. If you read the implementation notes for the Factory Method pattern, you’ll find that there are plenty of ways to implement a Factory Method. For example, the following diagram shows another way:

There Are Many Ways to Implement a Pattern

In this case, the Product class is abstract, while every other class is concrete. In addition, the Creator class implements its own factoryMethod() , which the ConcreteCreator overrides.

There are even more ways to implement the Factory Method pattern. Here’s another one:

There Are Many Ways to Implement a Pattern

In this case, the Product class is concrete and has no subclass. The Creator , which is abstract, defines an abstract version of the Factory Method, which the ConcreteCreator implements to return an instance of Product .

The main point? There are many ways to implement a pattern.

Unfortunately, when programmers look at the solitary Structure diagram accompanying each pattern in the Design Patterns book, they often jump to the conclusion that the Structure diagram is the way to implement the pattern. If they’d only read the crucial implementation notes, they’d know better. Yet many a programmer picks up Design Patterns , gazes at a Structure diagram, and then begins coding. The result is code that exactly mirrors the Structure diagram, instead of a pattern implementation that best matches the need at hand.

A few years after the publication of Design Patterns , John Vlissides, one of the book’s coauthors, wrote:

It seems you can’t overemphasize that a pattern’s Structure diagram is just an example, not a specification. It portrays the implementation we see most often. As such the Structure diagram will probably have a lot in common with your own implementation, but differences are inevitable and actually desirable. At the very least you will rename the participants as appropriate for your domain. Vary the implementation trade-offs, and your implementation might start looking a lot different from the Structure diagram. [ Vlissides ]

In this book, you’ll find pattern implementations that look quite different from their Structure diagrams in Design Patterns . For example, here’s the Structure diagram for the Composite pattern:

There Are Many Ways to Implement a Pattern

And here is a particular implementation of the Composite pattern:

There Are Many Ways to Implement a Pattern

As you can see, this implementation of Composite bears little resemblance to the Structure diagram for Composite. It is a minimalistic Composite implementation that resulted from coding only what was necessary.

Being minimalistic in your pattern implementations is part of the practice of evolutionary design. In many cases, a non-patterns-based implementation may need to evolve to include a pattern. In that case, you can refactor the design to a simple pattern implementation. I use this approach throughout this book.

Refactoring to, towards, and away from Patterns

Good designers refactor in many directions, always with the goal of reaching a better design. While many of the refactorings I apply don’t involve patterns (i.e., they’re small, simple transformations, like Extract Method [ F ], Rename Method [ F ], Move Method [ F ], Pull Up Method [ F ], and so forth), when my refactorings do involve patterns, I refactor to, towards, and even away from patterns.

The direction a pattern-directed refactoring takes is often influenced by the nature of a pattern. For example, Compose Method (123) is a refactoring based on Kent Beck’s Composed Method [ Beck, SBPP ] pattern. When I apply Compose Method (123) , which I do often, I refactor to a Composed Method, not towards one. Refactoring towards a Composed Method doesn’t sufficiently improve a method. You must refactor all the way to this pattern to achieve a genuine improvement.

The same is true of the Template Method pattern [ DP ]. People generally apply the refactoring Form Template Method (205) to remove duplicate code in subclasses. You can’t refactor towards a Template Method and expect to remove duplication. Either you implement a Template Method or you don’t, and if you don’t, you won’t be removing duplicate code in your subclasses.

On the other hand, this book contains numerous refactorings that provide acceptable design improvements whether you go towards or all the way to a pattern implementation. Move Embellishment to Decorator (144) provides a good example. An early step in the mechanics for this refactoring suggests that you use the Replace Conditional with Polymorphism [ F ] refactoring. Once you’ve done that, you can decide whether you’ve made a good enough design improvement to stop. If you happen to see a benefit from taking the next step, the mechanics suggest that you use the Replace Inheritance with Delegation [ F ] refactoring. If doing so provides a sufficient design improvement, you can stop. Or, if you see a benefit in applying all of the mechanics, you will refactor all the way to a Decorator.

Similarly, if you suspect that you need to use Replace Conditional Dispatcher with Command (191) , the steps you take towards a Command [ DP ] implementation can improve your design, regardless of whether you refactor all the way to the Command pattern.

Once you’ve refactored to or towards a pattern, you must evaluate whether your design has indeed improved. If it hasn’t, you’d better backtrack or refactor in another direction, such as away from a pattern or to another pattern. Inline Singleton (114) removes the Singleton [ DP ] pattern from a design. Encapsulate Composite with Builder (96) changes client code to interact with a Builder [ DP ] rather than a Composite. Move Accumulation to Visitor (320) replaces awkward and/or duplication-ridden Iterator [ DP ] code with a Visitor [ DP ] solution.

By applying the refactorings in this book, you may refactor to, towards, or away from patterns. Just remember that the goal is always to obtain a better design, not to implement patterns. Table 3.1 lists the directions I often take when applying the patterns-based refactorings in this book.

Table 3.1

Image

Image

Do Patterns Make Code More Complex?

One team I worked with included programmers who knew patterns and programmers who didn’t know patterns. Bobby knew patterns well and had ten years of programming experience. John had little exposure to patterns and had four years of programming experience.

One day John looked over a significant refactoring Bobby had completed and exclaimed, “I liked the code better before! Now the code is way more complex!”

Bobby had refactored a large amount of conditional logic associated with validating data entry screens. His refactoring led him to the Composite pattern. Bobby had converted many pieces of validation logic into separate validation objects, all of which shared the same interface. For a given data entry screen, the appropriate validation objects were now assembled into a single Composite validation object. At runtime, a data entry screen’s Composite validation object would be queried to discover which validation rules passed or failed.

I happened to be pair-programming with John when he expressed his discontent with Bobby’s refactoring. I wanted to understand the root of John’s discontent, so I asked John some questions. I quickly learned that John was not familiar with the Composite pattern. That explained a lot.

John was open to learning the Composite pattern when I offered to teach it to him. After I felt that he had grasped the pattern, we went back to looking over Bobby’s refactored code. I then asked John whether he felt differently about the refactoring. Reluctantly, he agreed that the code wasn’t as complex as he had thought, yet he didn’t go so far as to say it was better than the previous code.

From my perspective, Bobby’s refactoring represented a vast improvement over the previous code. Bobby had removed large chunks of conditional logic and duplicate code in classes associated with data entry screens. He had also dramatically simplified the way to discover passing and failing validation rules.

My own comfort and familiarity with the Composite pattern influenced my perspective on Bobby’s refactoring. Unlike John, I found the refactored code to be simpler and cleaner than the previous code.

In general, pattern implementations ought to help remove duplicate code, simplify logic, communicate intention, and increase flexibility. However, as this story reveals, people’s familiarity with patterns plays a major role in how they perceive patterns-based refactorings. I prefer that teams learn patterns rather than avoid using them because the teams view patterns as being too complex. On the other hand, some pattern implementations can make code more complex than it needs to be; when that happens, backtracking or more refactoring is necessary.

Pattern Knowledge

If you don’t know patterns, you’re less likely to evolve great designs. Patterns capture wisdom. Reusing that wisdom is extremely useful.

Maynard Solomon, a biographer of Mozart, observed that Mozart didn’t invent new forms of music—he simply combined existing forms to produce stunningly good results [ Solomon ]. Patterns are like new forms of music you can use and combine to produce excellent software designs.

Knowledge of the Builder pattern once played a crucial role in the evolution of a system I helped develop. The system needed to run in two completely different environments. Had we not evolved the system to use the Builder pattern relatively early in our design, I shudder to think of how our design would have turned out.

JUnit, an excellent testing framework that enables test-driven development and unit testing, is dense with patterns. Its authors, Kent Beck and Erich Gamma, didn’t try to put as many patterns into JUnit as they could. They simply evolved the framework and reused the wisdom of patterns as they designed. Since JUnit is an open source tool, I’ve been able to follow its evolution from version 1.0 to the latest version. By studying each version and by talking to Kent and Erich about their work, I can tell you that they definitely refactored to and towards patterns. Their knowledge of patterns most certainly aided them in their refactoring work.

Yet as I mentioned at the start of this book, having knowledge of patterns isn’t enough to evolve great software. You must also know how to intelligently use patterns, which is the subject of this book. Nevertheless, if you don’t study patterns, you’ll lack access to important, even beautiful, design ideas.

My preferred way to gain knowledge of patterns is to choose great pattern books to study and then study one pattern a week in a study group. “Pools of Insight” [ Kerievsky, PI ], a pattern language I once wrote, describes how to set up a long-lasting patterns study group.

A study group I founded in 1995, called the Design Patterns Study Group of New York City, is still going strong today. The Silicon Valley Patterns Group is another long-running patterns study group. Some of its members enjoy it so much that they’ve actually moved closer to where the group meets, to make it easier to attend meetings.

Folks in these study groups love to become better software designers. Meeting and discussing important design ideas each week is a great way to do that.

If you think there are already too many patterns books to study, don’t worry. Follow the advice of Jerry Weinberg. I once asked him how he keeps up with all the books that come out. He said, “Easy—I only read the great ones.”

Up-Front Design with Patterns

In spring 1996, a well-known music and television company sought to create a Java version of its Web site. The company’s managers knew how they wanted the site to look and behave but lacked the Java expertise to build the site. So they began looking for a development partner.

Industrial Logic, my company, was contacted by this organization. At our first meeting, I was led through the user interface design. I also learned that the company would want to modify the behavior of the future site without having to call programmers to make every little change. The managers had one question for me: How would I program the site to meet their needs?

Over the next few weeks, I worked with my colleagues to consider designs for the site. All of us were members of the Design Patterns Study Group I had started six months earlier. Our newfound knowledge of patterns was most helpful in our design work. For each of the requirements of the site, we considered what patterns could help us.

It soon became apparent that the Command [ DP ] pattern would play an essential role in our design. We would program the site in such a way that Command objects would control all behavior. If you clicked somewhere on the screen, a Command object (or many Command objects) would execute. We’d also invent a simple Interpreter [ DP ] to allow our clients to configure their site to run whatever Command objects they wanted, thereby allowing them to modify their site’s behavior without having to call us.

We spent several days documenting our design. Then we had a second big meeting with the music and television folks. The meeting went well and we were asked to return for a third meeting to get into more technical details about our design.

As the weeks ticked by, we had our next meeting and then our next one. By mid-summer, we had not programmed any code for the site; we simply had a growing body of design documents. Finally, sometime in mid-August, we learned that we had won the bid to develop the site.

Over the coming months, we programmed the site, following our design very closely. As we programmed, we found places where we could improve the design by refactoring to the Composite [ DP ], Iterator [ DP ], and Null Object [ Woolf ] patterns. For an example of how and why we refactored to Null Object, see the discussion in Introduce Null Object (301) .

By mid-December, about one month beyond the scheduled delivery date, we were done. The site went live. We all celebrated.

I often think of this experience when I consider refactoring and the role of patterns. If we had to do it all over again, would it have been better to evolve our design, instead of doing big design up-front ( BDUF )? Would we have been more successful had we exclusively refactored to or towards patterns rather than using a few patterns early in our design?

No. We would not have won the bid for this project had we not thought of a design and presented it, in detail, to the client. BDUF was essential in this context, and our up-front design with the Command and Interpreter patterns was a critical part of our success.

The typical problem with BDUF is that it often wastes time. You come up with a design for requirements and then those requirements change, get dropped, or are deferred to some later date. Or your requirements don’t change, but you spend lots of time coming up with a design that’s more elegant or sophisticated than it needs to be.

In this case, we didn’t encounter such BDUF problems. Our project was small with very fixed requirements. We used every aspect of our up-front design in our programming work. Our code did just what our clients needed and wasn’t overly complicated or sophisticated.

However, we were late to deliver the site by one month because of numerous defects we encountered in the Internet browsers. We began testing the Mac version of the site midway through the project and soon found that Netscape on the Mac had serious defects that we needed to program around. In addition, we encountered numerous differences between Internet Explorer and Netscape, which caused us to make many time-consuming modifications to our code.

Being one month late to deliver wasn’t a serious problem, though it did cause us some stress. If we had begun programming sooner, before we won the bid, we may have encountered the browser defects earlier. Yet at the time we were reluctant to code anything until we had a client who would pay us for our work.

Since 1996, I’ve done very little up-front design with patterns. The approach I’ve taken on project after project has been to evolve a system, refactoring to, towards, or away from patterns as necessary. The Command pattern remains the major exception. Since 1996, I’ve used it on two or three systems very early in a design because it was easy to implement and the systems clearly required the behavior supplied by the Command pattern.

I included this story in this chapter because I believe it helps illustrate when it makes sense to ignore the ideas in this book. While I don’t generally favor up-front design with patterns, I know that it has some place in a designer’s toolkit. I use up-front design with patterns rarely and most judiciously, and I recommend you do so as well.