Design Patterns Explained - Shalloway & Trott (2nd Edition)
Design Patterns Explained - Shalloway & Trott (2nd Edition)
—CLIF NOCK
—JAMES HUDDLESTON
This page intentionally left blank
Design Patterns
Explained
The Software Patterns Series
Series Editor: John M. Vlissides
The Software Patterns Series (SPS) comprises pattern literature of lasting significance to
software developers. Software patterns document general solutions to recurring problems
in all software-related spheres, from the technology itself, to the organizations that develop
and distribute it, to the people who use it. Books in the series distill experience from one
or more of these areas into a form that software professionals can apply immediately.
Relevance and impact are the tenets of the SPS. Relevance means each book presents patterns
that solve real problems. Patterns worthy of the name are intrinsically relevant; they are
borne of practitioners’ experiences, not theory or speculation. Patterns have impact when
they change how people work for the better. A book becomes a part of the series not just
because it embraces these tenets, but because it has demonstrated it fulfills them for its
audience.
Design Patterns Explained, Second Edition: A New Perspective on Object-Oriented Design; Alan Shalloway
and James Trott
Pattern Languages of Program Design 2; John M. Vlissides, James O. Coplien, and Norman L. Kerth
Pattern Languages of Program Design 3; Robert C. Martin, Dirk Riehle, and Frank Buschmann
Pattern Languages of Program Design 5; Dragos Manolescu, Markus Voelter, and James Noble
Patterns for Parallel Programming; Timothy G. Mattson, Beverly A. Sanders, and Berna L. Massingill
Software Configuration Management Patterns: Effective Teamwork, Practical Integration; Stephen P. Berczuk
and Brad Appleton
The Design Patterns Smalltalk Companion; Sherman Alpert, Kyle Brown, and Bobby Woolf
Use Cases: Patterns and Blueprints; Gunnar Övergaard and Karin Palmkvist
For more information, check out the series web site at www.awprofessional.com/series/swpatterns
Design Patterns
Explained
A New Perspective on Object-Oriented Design
Second Edition
Alan Shalloway
James R. Trott
ISBN-10: 0-321-24714-0
ISBN-13: 978-0-321-24714-8
Text printed on recycled paper
1 2 3 4 5 6 7 8 9 10—MA—0605040302
Sixth printing, October 2007
To Leigh, Bryan, Lisa, Michael, and Steven
for their love, support,
encouragement, and sacrifice.
—Alan Shalloway
—James R. Trott
This page intentionally left blank
Contents
Preface ______________________________________________xix
From Object Orientation to Patterns to True Object
Orientation ___________________________________________xxi
From Artificial Intelligence to Patterns to True Object
Orientation_________________________________________xxviii
A Note About Conventions Used in This Book _______________xxx
Feedback ______________________________________________xxxiv
New in the Second Edition_______________________________xxxiv
Acknowledgments_______________________________________xxxv
PART I
An Introduction to Object-Oriented Software
Development __________________________________________1
Chapter 1
The Object-Oriented Paradigm _____________________3
Overview _________________________________________________3
Before the Object-Oriented Paradigm: Functional Decomposition 4
The Problem of Requirements ________________________________6
Dealing with Changes: Using Functional Decomposition _________8
Dealing with Changing Requirements ________________________11
The Object-Oriented Paradigm ______________________________15
Object-Oriented Programming in Action______________________23
Special Object Methods ____________________________________27
Summary_________________________________________________28
Review Questions _________________________________________30
ix
x Contents
Chapter 2
The UML—The Unified Modeling Language______33
Overview_________________________________________________33
What Is the UML? _________________________________________33
Why Use the UML? ________________________________________34
The Class Diagram _________________________________________35
Interaction Diagrams_______________________________________42
Summary_________________________________________________45
Review Questions _________________________________________45
PART II
The Limitations of Traditional Object-Oriented
Design ________________________________________________47
Chapter 3
A Problem That Cries Out for Flexible Code ____49
Overview_________________________________________________49
Extracting Information from a CAD/CAM System _____________49
Understand the Vocabulary _________________________________50
Describe the Problem ______________________________________52
The Essential Challenges and Approaches_____________________55
Summary_________________________________________________58
Review Questions _________________________________________59
Chapter 4
A Standard Object-Oriented Solution_____________61
Overview_________________________________________________61
Solving with Special Cases __________________________________61
Summary_________________________________________________70
Review Questions _________________________________________71
Contents xi
PART III
Design Patterns _____________________________________73
Chapter 5
An Introduction to Design Patterns ______________75
Overview_________________________________________________75
Design Patterns Arose from Architecture and Anthropology ____76
Moving from Architectural to Software Design Patterns ________81
Why Study Design Patterns? _______________________________83
Other Advantages of Studying Design Patterns ________________88
Summary_________________________________________________90
Review Questions _________________________________________90
Chapter 6
The Facade Pattern ________________________________93
Overview_________________________________________________93
Introducing the Facade Pattern ______________________________93
Learning the Facade Pattern ________________________________94
Field Notes: The Facade Pattern _____________________________97
Relating the Facade Pattern to the CAD/CAM Problem _________99
Summary_________________________________________________99
Review Questions _________________________________________99
Chapter 7
The Adapter Pattern _______________________________101
Overview________________________________________________101
Introducing the Adapter Pattern____________________________101
Learning the Adapter Pattern ______________________________102
Field Notes: The Adapter Pattern ___________________________107
Relating the Adapter Pattern to the CAD/CAM Problem _______111
Summary _______________________________________________112
Review Questions ________________________________________112
xii Contents
Chapter 8
Expanding Our Horizons __________________________115
Overview________________________________________________115
Objects: The Traditional View and the New View _____________117
Encapsulation: The Traditional View and the New View _______119
Find What Is Varying and Encapsulate It ____________________123
Commonality and Variability Analysis and Abstract Classes ____127
The Qualities of Agile Coding ______________________________130
Summary _______________________________________________135
Review Questions ________________________________________136
Chapter 9
The Strategy Pattern ______________________________139
Overview________________________________________________139
An Approach to Handling New Requirements________________139
The International E-Commerce System Case Study:
Initial Requirements __________________________________142
Handling New Requirements ______________________________143
The Strategy Pattern ______________________________________152
Field Notes: Using the Strategy Pattern ______________________154
Summary _______________________________________________156
Review Questions ________________________________________157
Chapter 10
The Bridge Pattern ________________________________159
Overview________________________________________________159
Introducing the Bridge Pattern _____________________________159
Learning the Bridge Pattern: An Example ___________________161
An Observation About Using Design Patterns ________________172
Learning the Bridge Pattern: Deriving It _____________________173
The Bridge Pattern in Retrospect ___________________________183
Field Notes: Using the Bridge Pattern _______________________183
Summary _______________________________________________188
Review Questions ________________________________________191
Contents xiii
Chapter 11
The Abstract Factory Pattern ____________________193
Overview________________________________________________193
Introducing the Abstract Factory Pattern ____________________193
Learning the Abstract Factory Pattern: An Example___________194
Learning the Abstract Factory Pattern: Implementing It _______202
Field Notes: The Abstract Factory Pattern ____________________207
Relating the Abstract Factory Pattern to the CAD/CAM
Problem _____________________________________________211
Summary _______________________________________________211
Review Questions ________________________________________212
PART IV
Putting It All Together: Thinking in Patterns____215
Chapter 12
How Do Experts Design? _________________________217
Overview________________________________________________217
Building by Adding Distinctions ____________________________217
Summary _______________________________________________226
Review Questions ________________________________________226
Chapter 13
Solving the CAD/CAM Problem
with Patterns ______________________________________229
Overview________________________________________________229
Review of the CAD/CAM Problem__________________________229
Thinking in Patterns ______________________________________231
Thinking in Patterns: Step 1 _______________________________233
Thinking in Patterns: Step 2a ______________________________233
Thinking in Patterns: Step 2b ______________________________239
Thinking in Patterns: Step 2c_______________________________244
Thinking in Patterns: Steps 2a and 2b Repeated (Facade) ______244
xiv Contents
PART V
Toward a New Paradigm of Design _____________251
Chapter 14
The Principles and Strategies of Design
Patterns ____________________________________________253
Overview________________________________________________253
The Open-Closed Principle ________________________________254
The Principle of Designing from Context ____________________255
The Principle of Encapsulating Variation_____________________261
Abstract Classes vs. Interfaces ______________________________262
The Principle of Healthy Skepticism_________________________264
Summary _______________________________________________265
Review Questions ________________________________________266
Chapter 15
Commonality and Variability Analysis___________269
Overview________________________________________________269
Commonality and Variability Analysis and Application Design _269
Solving the CAD/CAM Problem with CVA ___________________270
Summary _______________________________________________277
Review Questions ________________________________________277
Chapter 16
The Analysis Matrix _______________________________279
Overview________________________________________________279
Contents xv
Chapter 17
The Decorator Pattern ___________________________297
Overview________________________________________________297
A Little More Detail_______________________________________297
The Decorator Pattern_____________________________________300
Applying the Decorator Pattern to the Case Study ____________301
Another Example: Input/Output ___________________________305
Field Notes: Using the Decorator Pattern ____________________307
The Essence of the Decorator Pattern _______________________309
Summary _______________________________________________310
Review Questions ________________________________________310
PART VI
Other Values of Patterns _________________________313
Chapter 18
The Observer Pattern _____________________________315
Overview________________________________________________315
Categories of Patterns _____________________________________315
More Requirements for the International E-Commerce
Case Study ___________________________________________317
The Observer Pattern _____________________________________319
Applying the Observer to the Case Study ____________________319
Field Notes: Using the Observer Pattern _____________________325
Summary _______________________________________________327
Review Questions ________________________________________328
xvi Contents
Chapter 19
The Template Method Pattern ___________________331
Overview________________________________________________331
More Requirements for the International E-Commerce
Case Study ___________________________________________331
The Template Method Pattern______________________________332
Applying the Template Method to the International
E-Commerce Case Study ______________________________333
Using the Template Method Pattern to Reduce Redundancy ___334
Field Notes: Using the Template Method Pattern______________340
Summary _______________________________________________341
Review Questions ________________________________________343
PART VII
Factories ___________________________________________345
Chapter 20
Lessons from Design Patterns: Factories _____347
Overview________________________________________________347
Factories ________________________________________________347
The Universal Context Revisited____________________________349
Factories Follow Our Guidelines____________________________351
Limiting the Vectors of Change_____________________________353
Another Way to Think About It ____________________________354
Different Roles of Factories ________________________________355
Field Notes ______________________________________________355
Summary _______________________________________________356
Review Questions ________________________________________356
Overview________________________________________________359
Chapter 21
The Singleton Pattern and the Double-Checked
Locking Pattern ___________________________________359
Introducing the Singleton Pattern __________________________360
Contents xvii
Chapter 22
The Object Pool Pattern __________________________371
Overview________________________________________________371
A Problem Requiring the Management of Objects ____________372
The Object Pool Pattern ___________________________________381
Observation: Factories Can Do Much More Than Instantiation _381
Summary _______________________________________________384
Review Questions ________________________________________384
Chapter 23
The Factory Method Pattern_____________________385
Overview________________________________________________385
More Requirements for the Case Study _____________________385
The Factory Method Pattern _______________________________386
Factory Method Pattern and Object-Oriented Languages ______387
Field Notes: Using the Factory Method Pattern _______________388
Summary _______________________________________________390
Review Questions ________________________________________390
Chapter 24
Summary of Factories ____________________________393
Overview________________________________________________393
Steps in the Software Process ______________________________393
Parallels in Factories and XP Practices _______________________395
Scaling Systems __________________________________________395
xviii Contents
PART VIII
Endings and Beginnings__________________________397
Chapter 25
Design Patterns Reviewed: A Summation
and a Beginning ___________________________________399
Overview________________________________________________399
A Summary of Object-Oriented Principles ___________________400
How Design Patterns Encapsulate Implementations ___________401
Commonality and Variability Analysis and Design Patterns ____401
Decomposing a Problem Domain into Responsibilities_________402
Patterns and Contextual Design ____________________________403
Relationships Within a Pattern _____________________________404
Design Patterns and Agile Coding Practices __________________405
Field Notes ______________________________________________406
Summary _______________________________________________407
Review Questions ________________________________________408
Chapter 26
Bibliography________________________________________409
Design Patterns Explained: The Web Site Companion _________410
Recommended Reading __________________________________410
Recommended Reading for Java Programmers _______________412
Recommended Reading for C++ Programmers _______________413
Recommended Reading for COBOL Programmers ____________414
Recommended Reading on eXtreme Programming ___________414
Recommended Reading on General Programming ____________415
Personal Favorites ________________________________________415
Index ________________________________________________419
Preface
Since the first edition was written, we have learned so much more
about design patterns, including the following:
This book covers all of these topics. We have deepened and clari-
fied what we had before and have added some new content that
you will find very helpful, including the following:
xix
xx Preface
We can honestly say this is one of the few second editions that is
definitely worth buying — even if you have the first one.
As you read this book, you will gain a solid understanding of 12 core
design patterns and a pattern used in analysis. You will learn that
design patterns do not exist in isolation, but work in concert with
other design patterns to help you create more robust applications.
You will gain enough of a foundation that you will be able to read the
design pattern literature, if you want to, and possibly discover patterns
on your own. Most importantly, you will be better equipped to cre-
ate flexible and complete software that is easier to maintain.
Although the 12 patterns we teach here are not all of the patterns you
should learn, an understanding of these will enable you to learn the
others on your own more easily. Instead of giving you more patterns
than you need to get started, we have included pattern-related is-
sues that will be more useful.
Now, looking back, I see that I really did not understand the full ca-
pabilities of object-oriented design, even though I was doing things
the way most experts advised. It wasn’t until I began to learn design
patterns that my object-oriented design abilities expanded and deep-
ened. Knowing design patterns has made me a better designer, even
when I don’t use these patterns directly.
When I looked at my work at the time, however, I saw that I was not
incorporating any design patterns into my code. Or, at least, not con-
sciously. Later, after learning patterns, I realized I had incorporated
many design patterns into my code just out of being a good coder.
However, now that I understand patterns better, I am able to use
them better.
I just figured I didn’t know enough design patterns yet and needed
to learn more. At the time, I only knew about six of them. Then I had
an epiphany. I was working as a mentor in object-oriented design
Preface xxiii
for a project and was asked to create the project’s high-level design.
The leader of the project was extremely sharp, but was fairly new to
object-oriented design.
The problem itself wasn’t that difficult, but it required a great deal of
attention to make sure the code was going to be easy to maintain.
Literally, after about two minutes of looking at the problem, I had de-
veloped a design based on my normal approach of data abstraction.
Unfortunately, it was also clear to me this was not going to be a good
design. Data abstraction alone had failed me. I had to find something
better.
Two hours later, after applying every design technique I knew, I was
no better off. My design was essentially the same. What was most
frustrating was that I knew there was a better design. I just couldn’t
see it. Ironically, I also knew of four design patterns that “lived” in my
problem, but I couldn’t see how to use them. Here I was—a supposed
expert in object-oriented design—baffled by a simple problem!
Feeling very frustrated, I took a break and started walking down the
hall to clear my head, telling myself I would not think of the prob-
lem for at least 10 minutes. Well, 30 seconds later, I was thinking
about it again! But I had gotten an insight that changed my view of
design patterns: rather than using patterns as individual items, I
should use the design patterns together.
I had heard this before, but hadn’t really understood it. Because pat-
terns in software have been introduced as design patterns, I had always
labored under the assumption that they had mostly to do with design.
My thoughts were that in the design world, the patterns came as
pretty much well-formed relationships between classes. Then I read
Christopher Alexander’s amazing book, The Timeless Way of Building
(Oxford University Press, 1979). I learned that patterns existed at all
levels—analysis, design, and implementation. Alexander discusses
xxiv Preface
When I stepped back and used design patterns and Alexander’s ap-
proach to guide me in the creation of my classes, a far superior solu-
tion unfolded in only a matter of minutes. It was a good design, and
we put it into production. I was excited—excited to have designed a
good solution and excited about the power of design patterns. It was
then that I started incorporating design patterns into my develop-
ment work and my teaching.
Imagine my surprise! The design pattern books I had been reading and
the design pattern experts I had been talking to were saying that you
really needed to have a good grounding in object-oriented design be-
fore embarking on a study of design patterns. Nevertheless, I saw,
with my own eyes, students who learned object-oriented design con-
currently with design patterns learned object-oriented design faster
than those just studying object-oriented design. They even seemed to
learn design patterns at almost the same rate as experienced object-
oriented practitioners.
Preface xxv
Since the first edition of this book appeared, I have been doing a
considerable amount of agile development and have become very
grounded in eXtreme Programming (XP) coding practices, test-
driven development (TDD), and Scrum. Initially, I had a difficult
xxvi Preface
I found that I was using these principles in my own designs both with
and without patterns. This didn’t surprise me. If using these strate-
gies resulted in a design equivalent to a design pattern when I knew
the pattern was present, that meant they were giving me a way to
derive excellent designs (because patterns are excellent designs by
Preface xxvii
definition). Why would I get any poorer designs from these techniques
just because I didn’t know the name of the pattern that might or might
not be present anyway?
I relate this story because this book follows much the same pattern
as my course (pun intended). Virtually all the material in this book
now is covered in one of our courses on design patterns, test-driven-
development or agile development best practices.1
As you read this book, you will learn the patterns. Even more impor-
tantly, you will learn why they work and how they can work together,
and the principles and strategies upon which they rely. It will be useful
to draw on your own experiences. When I present a problem in the
text, it is helpful if you imagine a similar problem that you have come
across. This book isn’t about new bits of information or new patterns to
apply, but rather a new way of looking at object-oriented software de-
velopment. I hope that your own experiences, connected with the prin-
ciples of design patterns, will prove to be a powerful ally in your learning.
Alan Shalloway
December 2000
Updated October 2004
began to apply KADS to her work in the United States. She extended
the European’s work to apply KADS to object-oriented systems. She
opened my eyes to an entire world of pattern-based analysis and de-
sign that was forming in the software world, in large part due to
Christopher Alexander’s work. Her book Cognitive Patterns (Cambridge
University Press, 1998) describes this work.
This last point is significant. Patterns help end users understand systems
because they provide the context for the system, why we are doing
things in a certain way. We can use patterns to describe the guiding
principles and strategies of the system. And we can use patterns to de-
velop the best examples to help end users understand the system.
I was hooked.
Since writing the first edition, I have learned just how deeply this
approach to analysis can get into your head. I have been involved in
many different sorts of projects, many outside of software develop-
ment. I look at systems of people working together, exchanging
knowledge, exchanging ideas, living in remote places. The principles
of patterns and object orientation have stood me well here, too. Just
as in computer systems, much efficiency is to be gained by reducing
the dependencies among work systems.
I hope that the principles in this book help you in your own journey
to become a more effective and efficient analyst.
James R. Trott
December 2000
Updated October 2004
Approach Rationale
First person voice This book is a collaborative effort between two au-
thors. We debated and refined our ideas to find the
best ways to explain these concepts. Alan tried
them out in his courses, and we refined some
more. We chose to use the first person singular in
the body of this book because it enables us to tell
the story in what we hope is a more engaging and
natural style.
Preface xxxi
Approach Rationale
Scanning text We have tried to make this book easy to scan so that
you can get the main points even if you do not read
the full body of text, or so that you can quickly find the
information you need. We make significant use of ta-
bles and bulleted lists. We provide text in the outside
margin that summarizes paragraphs. With the discus-
sion of each pattern, we provide a summary table of
the key features of the pattern. Our hope is that these
will make the book that much more accessible.
Code examples This book is about analysis and design more than
implementation. Our intent is to help you think
about crafting good designs based on the insights
and best practices of the object-oriented communi-
ty, as expressed in design patterns. One of the
challenges for all of us programmers is to avoid
going to the implementation too early, doing before
thinking. Knowing this, we have purposefully tried
to stay away from too much discussion on imple-
mentation. Our code examples may seem a bit
lightweight and fragmentary. Specifically, we never
provide error checking in the code. This is because
we are trying to use the code to illustrate concepts.
However, the book’s companion Web site, at
http://www.netobjectives.com/dpexplained, con-
tains more complete code examples from which
the fragments were extracted. Examples in C++
and C# are also present at this site.
Show breadth and We are trying give you a taste for design patterns,
give a taste to expose you to the breadth of the pattern world
but not go into depth in any of them (see the previ-
ous point).
xxxii Preface
Approach Rationale
Show breadth and We are trying give you a taste for design patterns,
give a taste (cont.) Our thought was this: If you brought someone to
the United States for a two-week visit, what would
you show that person? Maybe a few sites to help
him get familiar with architectures, communities,
the feel of cities and the vast spaces that separate
them, freeways, and coffee shops. But you would
not be able to show him everything. To fill in his
knowledge, you might choose to show him slide
shows of many other sites and cities to give him a
taste of the country. Then he could make plans for
future visits. Likewise, we are showing you the
major sites in design patterns, and then giving you
tastes of other areas, so that you can plan your
own journey into patterns.
All the code examples in this book are written in Java. If you do
not have experience with Java but can read C#, here is what you
need to know:
or
public class NewClass implements AnInterface
or
Preface xxxiii
All methods are virtual in Java, and therefore you don’t specify
whether they are new or overridden. There are no such key-
words in Java; all subclass methods override any methods they
reimplement from a base class. Although there are other differ-
ences, they won’t show up in our code examples.
This is a little more difficult, but not much more. The most obvi-
ous difference is the lack of header files. But how to read the com-
bined header-code file is self-evident. In addition to the C#
differences, Java never stores objects on the stack. Java stores ob-
jects in heap storage and stores variables that hold references
(pointers) to objects on the stack. Every object must be created
with a new.
Thus Java code looks like C++ code if you add an asterisk (*) in the
declaration of every variable name that references an object and
convert the period (.) to a hyphen followed by a right-angle brack-
et (->).
xxxiv Preface
Feedback
Please visit us at the Net Objectives companion Web site for this book;
the URL is http://www.netobjectives.com/dpexplained. At this site,
you will find our latest research as well as a discussion group relat-
ed to this book and to software development in general. Please post
corrections, comments, insights, and “aha” moments to this discus-
sion group.
• A design pattern not in the Gang of Four: the Object Pool pattern.
Acknowledgments
• Scott Bain, our colleague who patiently reviewed this work and
gave us insights. His collaboration with Alan at Net Objectives
also led to many of the new insights in the second edition of this
book.
• And especially Leigh and Jill, our patient wives, who put up with
us and encouraged us in our dream of this book.
• Sharon and Dr. Bob Foote, now teaching at West Point, who fos-
tered in me an insatiable curiosity and an abiding interest in peo-
ple. Their love and encouragement endure as patterns in me, as
a person, a husband and father, and as an analyst.
Part Overview
This part introduces you to a method for developing object-orient- In this part
ed software that is based on patterns—the insights and best practices
learned by designers and users over the years—and on the model-
ing language (UML) that supports this method.
I will not follow the approach of the 1980s, where developers were
simply told to “find the nouns in the requirement statements and
make them into objects.” In that approach, encapsulation was defined
as “data hiding,” and objects were defined as “things with data and
behavior used to access and manipulate those data.” This was (and
is) a limited view, constrained as it is by a focus on how to implement
objects. It is incomplete.
1
This page intentionally left blank
CHAPTER 1
The Object-Oriented
Paradigm
Overview
This chapter introduces you to the object-oriented paradigm by com- In this chapter
paring and contrasting it with something familiar: standard struc-
tured programming.
In this chapter
You could take any one of these steps and break it down further into
the steps required to implement it. For example, you could break
down Step 4. For each shape in the list, do the following:
4c. Call the appropriate function that will display the shape, giv-
ing it the shape’s location.
Another problem with functional decomposition is that it does not The challenge with
help us prepare the code for possible changes in the future, for a this approach:
graceful evolution. When change is required, it is often because I Dealing with change
want to add a new variation to an existing theme. For example, I
might have to deal with new shapes or new ways to display shapes.
If I have put all the logic that implements the steps into one large
function or module, virtually any change to the steps will require
changes to that function or module.
Verify this assertion for yourself. Think of a time when you wanted
to make a change to your code, but were afraid to put it in because
you knew that modifying the code in one place could break it some-
where else. Why might this happen? Must the code pay attention to
all of its functions and how they might be used? How might the
functions interact with one another? Were there too many details for
the function to pay attention to, such as the logic it was trying to
implement, the things with which it was interacting, the data it was
using? Just as with people, programs trying to focus on too many
things simultaneously beg for errors when anything changes.
Programming is a complex, abstract, dynamic activity.
6 Part I • An Introduction to Object-Oriented Software Development
And no matter how hard you try, no matter how well you do your
analysis, you can never get all of the requirements from the user. Too
much is unknown about the future. Things change. They always do…
And nothing you can do will stop change. But you do not have
to be overcome by it.
Requirements Ask software developers what they know to be true about the re-
always change quirements they get from users. They often answer the following:
One thing you will never hear is, “Not only were our requirements
complete, clear, and understandable, but they laid out all of the func-
tionality we were going to need for the next five years!”
I have also learned that most developers think this is a bad thing. But
few of them write their code to handle changing requirements well.
This does not mean you and I can give up on gathering good re-
quirements. It does mean that we must write our code to accom-
modate change. It also means we should stop beating ourselves up
(or our customers, for that matter) for things that will naturally occur.
You can design your code so that the impact of changing require-
ments is much less dramatic. Your code may evolve or new code
can be bolted on with little impact.
8 Part I • An Introduction to Object-Oriented Software Development
Using modularity to Look a little closer at the problem of displaying shapes. How can I
isolate variation write the code so that it is easier to handle shifting requirements?
Instead of writing one large function, I could make it more modular.
Problems with Then, when I receive a requirement to be able to display a new type
modularity in a of shape—a triangle, for instance—I only need to change this mod-
functional ule (hopefully!).
decomposition
approach This approach presents some problems, however. For example, I said
that the inputs to the module were the type of shape and a descrip-
tion of the shape. Depending upon how I am storing shapes, it may
or may not be possible to have a consistent description of shapes that
will work well for all shapes. What if the description of the shape is
sometimes stored as an array of points and sometimes is stored an-
other way? Would that still work?
With the approach that I have used so far, I find that I have two sig- Weak cohesion, tight
nificant problems, which go by the terms weak cohesion and tight cou- coupling
pling. In his book Code Complete (Microsoft Press, 1993), Steve
McConnell gives an excellent description of both cohesion and cou-
pling. He says:
2. Ibid, p. 87.