The great thing about software patterns is that they convey many useful design ideas. It follows, therefore, that if you learn a bunch of these patterns, you’ll be a pretty good software designer, right? I considered myself just that once I’d learned and used dozens of patterns. They helped me develop flexible frameworks and build robust and extensible software systems. After a couple of years, however, I discovered that my knowledge of patterns and the way I used them frequently led me to over-engineer my work.
Once my design skills had improved, I found myself using patterns in a different way: I began refactoring to, towards, and away from patterns, instead of using them for up-front design or introducing them too early into my code. My new way of working with patterns emerged from my adoption of extreme programming ( XP ) design practices, which helped me avoid both over- and under-engineering.
Over-Engineering
When you make your code more flexible or sophisticated than it needs to be, you over-engineer it. Some programmers do this because they believe they know their system’s future requirements. They reason that it’s best to make a design more flexible or sophisticated today, so it can accommodate the needs of tomorrow. That sounds reasonable—if you happen to be psychic.
If your predictions are wrong, you waste precious time and money. It’s not uncommon to spend days or weeks fine-tuning an overly flexible or unnecessarily sophisticated software design, leaving you with less time to add new behavior or remove defects.
What typically happens with code you produce in anticipation of needs that never materialize? It never gets removed. This happens either because it’s inconvenient to remove the code or because you expect that one day the code might be needed. Regardless of the reason, as overly flexible or unnecessarily sophisticated code accumulates, you and the rest of the programmers on your team, especially new ones, must operate within a code base that’s bigger and more complicated than it needs to be.
To compensate, folks decide to work in discrete areas of a system. This seems to make their jobs easier, yet it has the unpleasant side effect of generating lots of duplicate code because everyone works in his or her own comfortable area of the system, rarely seeking elsewhere for code that already does what he or she needs.
Over-engineered code affects productivity because when programmers inherit an over-engineered design, they must spend time learning the nuances of that design before they can comfortably extend or maintain it.
Over-engineering tends to happen quietly; many architects and programmers aren’t even aware they are doing it. And while their organizations may discern a decline in team productivity, few know that over-engineering plays a role in the problem.
Perhaps the main reason programmers over-engineer is that they don’t want to get stuck with a bad design. A bad design can weave its way so deeply into code that improving it becomes an enormous challenge. I’ve been there, and that’s why up-front design with patterns appealed to me so much.
The Patterns Panacea
When I first began learning patterns, they represented a flexible, sophisticated, even elegant way to do object-oriented design that I very much wanted to master. After thoroughly studying numerous patterns and pattern languages, I used them to improve systems I had already built and to formulate designs for systems I was about to build. Because the results of these efforts were promising, I felt sure I was on the right path.
But over time, the power of patterns led me to lose sight of simpler ways to write code. After learning that there were two or three different ways to do a calculation, I’d immediately race towards implementing the Strategy pattern, when, in fact, a simple conditional expression would have been easier and faster to program—a perfectly sufficient solution.
On one occasion, my preoccupation with patterns became quite apparent. I was pair-programming, and my partner and I had written a class that implemented Java’s TreeModel interface in order to display a graph of Spec objects in a tree widget. Our code worked, but the tree widget was displaying each Spec object by calling its toString() method, which didn’t return the Spec information we wanted. We couldn’t change Spec ’s toString() method because other parts of the system relied on its contents. So we reflected on how to proceed. As was my habit, I considered which patterns could help. The Decorator pattern came to mind, and I suggested that we use it to wrap Spec with an object that could override the toString() method. My partner’s response to this suggestion surprised me. “Using a Decorator here would be like applying a sledgehammer to the problem when a few light taps with a small hammer would do.” His solution was to create a small class called NodeDisplay , whose constructor took a Spec instance and whose one public method, toString() , obtained the correct display information from the Spec instance. NodeDisplay took no time to program because it was less than 10 simple lines of code. My Decorator solution would have involved creating over 50 lines of code, with many repetitive delegation calls to the Spec instance.
Experiences like this made me aware that I needed to stop thinking so much about patterns and refocus on writing small, simple, understandable code. I was at a crossroads: I’d worked hard to learn patterns to become a better software designer, but now I needed to relax my reliance on them in order to become truly better.
Under-Engineering
Under-engineering is far more common than over-engineering. We under-engineer when we produce poorly designed software. This may occur for several reasons.
• We don’t have time, don’t make time, or aren’t given time to refactor.
• We aren’t knowledgeable about good software design.
• We’re expected to quickly add new features to existing systems.
• We’re made to work on too many projects at once.
Over time, under-engineered software becomes an expensive, difficult-to-maintain or unmaintainable mess. Brian Foote and Joseph Yoder, who authored a pattern language called Big Ball of Mud, describe such software like this:
Data structures may be haphazardly constructed, or even next to non-existent. Everything talks to everything else. Every shred of important state data may be global. Where state information is compartmentalized, it may be passed promiscuously about though Byzantine back channels that circumvent the system’s original structure.
Variable and function names might be uninformative, or even misleading. Functions themselves may make extensive use of global variables, as well as long lists of poorly defined parameters. The functions themselves are lengthy and convoluted, and perform several unrelated tasks. Code is duplicated. The flow of control is hard to understand, and difficult to follow. The programmer’s intent is next to impossible to discern. The code is simply unreadable, and borders on indecipherable. The code exhibits the unmistakable signs of patch after patch at the hands of multiple maintainers, each of whom barely understood the consequences of what he or she was doing. [ Foote and Yoder , 661]
While systems you’ve worked on may not be so gruesome, it’s likely you’ve done some under-engineering. I know I have. There’s simply an overwhelming urge to get code working quickly, and it’s often coupled with powerful forces that impede our ability to improve the design of our existing code. In some cases, we consciously don’t improve our code because we know (or think we know) it won’t have a long shelf life. Other times, we’re compelled to not improve our code because well-meaning managers explain that our organization will be more competitive and successful if we “don’t fix what ain’t broke.”
Continuous under-engineering leads to the “fast, slow, slower” rhythm of software development, which goes something like this.
1. You quickly deliver release 1.0 of a system with junky code.
2. You deliver release 2.0 of the system, and the junky code slows you down.
3. As you attempt to deliver future releases, you go slower and slower as the junky code multiplies, until people lose faith in the system, the programmers, and even the process that got everyone into this position.
4. Somewhere during or after release 4.0, you realize you can’t win. You begin exploring the option of a total rewrite.
This kind of experience is far too common in our industry. It’s costly and it makes organizations far less competitive than they could be. Fortunately, there is a better way.
Test-Driven Development and Continuous Refactoring
Test-driven development [ Beck, TDD ] and continuous refactoring, two of the many excellent XP practices, have dramatically improved the way I build software. I’ve found that these two practices have helped me and the organizations I’ve worked for spend less time over-engineering and under-engineering and more time creating high-quality, function-rich code, produced on time.
Test-driven development ( TDD ) and continuous refactoring enable the efficient evolution of working code by turning programming into a dialogue.
• Ask : You ask a question of a system by writing a test.
• Respond : You respond to the question by writing code to pass the test.
• Refine : You refine your response by consolidating ideas, weeding out inessentials, and clarifying ambiguities.
• Repeat : You keep the dialogue going by asking the next question.
This rhythm of programming put my head into a totally new place. By using TDD , instead of spending lots of time thinking about a design that would work for every nuance of a system, I now spend seconds or minutes making a primitive piece of behavior work correctly before refactoring and evolving it to the next necessary level of sophistication.
Kent Beck’s mantra of TDD and continuous refactoring is “red, green, refactor.” The colors refer to what you see when you write and run a test in a unit-testing tool (like JUnit). The process goes like this.
1. Red : You create a test that expresses what you expect your code to do. The test fails (turns red) because you haven’t created code to make the test pass.
2. Green : You program whatever is expedient to make the test pass (turn green). You don’t pain yourself to come up with a duplication-free, simple, clear design at this point. You’ll drive towards such a design later, when your test is passing and you can comfortably experiment with better designs.
3. Refactor : You improve the design of the code that passed the test.
Simple as this sounds, TDD and continuous refactoring turn the world of programming upside down. The inexperienced programmer may think, “Write a test for code that doesn’t exist? Write code that passes a test yet needs immediate refactoring? Is this a wasteful, haphazard approach to software development or what?”
Actually, it’s just the opposite. TDD and continuous refactoring provide a lean, iterative, and disciplined style of programming that maximizes focus, relaxation, and productivity. “Rapid unhurriedness” is how Martin Fowler describes it [as quoted in Beck, TDD ], while Ward Cunningham explains that it’s more about continuous analysis and design than it is about testing.
Learning the right rhythm of TDD and continuous refactoring requires practice. Tony Mobley, a programmer I know, described this style of development as a paradigm shift as great, if not greater, than moving from structured programming to object-oriented programming. However long it takes you to get used to this style of development, once you do, you’ll find that producing production code any other way feels odd, uncomfortable, even unprofessional. Many of us who program using TDD and continuous refactoring find that it helps us:
• Keep defect counts low
• Refactor without fear
• Produce simpler, better code
• Program without stress
To learn the ins and outs of TDD , study Test-Driven Development [ Beck, TDD ] or Test-Driven Development: A Practical Guide [ Astels ]. For a taste of what it’s like to do TDD , see the example sections from Replace Implicit Tree with Composite (178) and Encapsulate Composite with Builder (96) . To learn how to continuously refactor, you’ll want to study Refactoring [ F ] (particularly the first chapter) as well as the refactorings in this book.
Refactoring and Patterns
On various projects, I’ve observed what and how my colleagues and I refactor. While we use many of the refactorings described in Refactoring [ F ], we also find places where patterns help us improve our designs. At such times, we refactor to or towards patterns, being careful not to produce overly flexible or unnecessarily sophisticated solutions.
When I explored the motivations for applying pattern-directed refactorings, I found they are identical to the general motivations for implementing low-level refactorings: to reduce or remove duplication, to simplify what is complicated, and to make code better at communicating its intention.
This motivation can easily be missed if you study only a portion of a design pattern. For example, every pattern in Design Patterns [ DP ] includes a section known as the Intent. The authors of Design Patterns describe the Intent as follows: “A short statement that answers the following questions: What does the design pattern do? What is its rationale and intent? What particular design issues or problem does it address?” [ DP , 6]. Despite this description, the Intent sections for many design patterns only hint at the main problem the pattern solves. Instead, more of the focus is put on what the pattern does. Here are two examples.
Intent of Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. [ DP , 325]
Intent of State
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. [ DP , 315]
These Intent descriptions don’t say that a Template Method helps reduce or remove duplicated code in similar methods of subclasses in a hierarchy or that the State pattern helps simplify complex conditional state-changing logic. If programmers study all of the sections of a design pattern, particularly the Applicability section, they’ll learn about the problems the pattern addresses.
However, when using the Design Patterns book during design, many programmers, myself included, have read the Intent section of a pattern to see whether the pattern could provide a good fit for a given situation. This method of choosing a pattern doesn’t work as well as a method that helps you match a design problem to the problems addressed by a pattern. Why? Because patterns exist to solve problems, and learning whether they really can help in a given situation involves understanding what problems they help solve.
The refactoring literature tends to focus more on specific design problems than the patterns literature does. If you study the first page of a refactoring, you’ll see the kind of problem the refactoring helps solve. The catalog of pattern-directed refactorings presented in this book, which is a direct continuation of work started in Refactoring , is intended to help you see what kinds of specific problems the patterns help solve.
While this book bridges the gap between patterns and refactoring, the connection between the two was noted by the authors of Design Patterns in the conclusion to their great book:
Our design patterns capture many of the structures that result from refactoring. . . . Design patterns thus provide targets for your refactorings. [ DP , 354]
Martin Fowler makes a similar observation near the beginning of Refactoring :
There is a natural relation between patterns and refactorings. Patterns are where you want to be; refactorings are ways to get there from somewhere else. [ F , 107]
Evolutionary Design
Today, after having become quite familiar with patterns, the “structures that result from refactoring,” I know that understanding good reasons to refactor to or towards a pattern are more valuable than understanding the end result of a pattern or the nuances of implementing that end result.
If you’d like to become a better software designer, studying the evolution of great software designs will be more valuable than studying the great designs themselves. For it is in the evolution that the real wisdom lies. The structures that result from the evolution can help you, but without knowing why they were evolved into a design, you’re more likely to misapply them or over-engineer with them on your next project.
To date, our software design literature has focused more on teaching great solutions than on teaching evolutions to great solutions. We need to change that. As the great poet Goethe said, “That which thy fathers have bequeathed to thee, earn it anew if thou wouldst possess it.” The refactoring literature is helping us reacquire a better understanding of good design solutions by revealing sensible evolutions to those solutions.
If you want to get the most out of patterns, you must do the same thing: See patterns in the context of refactoring, not just as reusable elements that exist apart from refactoring. This is my primary reason for producing a catalog of pattern-directed refactorings.
By learning to evolve your designs, you can become a better software designer and reduce the amount of work you over- or under-engineer. TDD and continuous refactoring are the key practices of evolutionary design. Instill pattern-directed refactorings into your knowledge of how to refactor and you’ll find yourself even better equipped to evolve great designs.