Foreword xxi
replacing old ones. As Fred Brooks admonishes us, we should probably re-do major soft-
ware chunks from scratch every seven years or so to sweep away creeping cruft. Perhaps
we should update Brooks’ time constant to an order of weeks, days or hours instead of
years. That’s where detail lies.
There is great power in detail, yet there is something humble and profound about this
approach to life, as we might stereotypically expect from any approach that claims Japa-
nese roots. But this is not only an Eastern outlook on life; English and American folk wis-
dom are full of such admonishments. The Seiton quote from above flowed from the pen of
an Ohio minister who literally viewed neatness “as a remedy for every degree of evil.”
How about Seiso? Cleanliness is next to godliness. As beautiful as a house is, a messy
desk robs it of its splendor. How about Shutsuke in these small matters? He who is faithful
in little is faithful in much. How about being eager to re-factor at the responsible time,
strengthening one’s position for subsequent “big” decisions, rather than putting it off? A
stitch in time saves nine. The early bird catches the worm. Don’t put off until tomorrow
what you can do today. (Such was the original sense of the phrase “the last responsible
moment” in Lean until it fell into the hands of software consultants.) How about calibrat-
ing the place of small, individual efforts in a grand whole? Mighty oaks from little acorns
grow. Or how about integrating simple preventive work into everyday life? An ounce of
prevention is worth a pound of cure. An apple a day keeps the doctor away. Clean code
honors the deep roots of wisdom beneath our broader culture, or our culture as it once was,
or should be, and can be with attentiveness to detail.
Even in the grand architectural literature we find saws that hark back to these sup-
posed details. Think of mies van der Rohe’s doorknobs. That’s seiri. That’s being attentive
to every variable name. You should name a variable using the same care with which you
name a first-born child.
As every homeowner knows, such care and ongoing refinement never come to an end.
The architect Christopher Alexander—father of patterns and pattern languages—views
every act of design itself as a small, local act of repair. And he views the craftsmanship of
fine structure to be the sole purview of the architect; the larger forms can be left to patterns
and their application by the inhabitants. Design is ever ongoing not only as we add a new
room to a house, but as we are attentive to repainting, replacing worn carpets, or upgrad-
ing the kitchen sink. Most arts echo analogous sentiments. In our search for others who
ascribe God’s home as being in the details, we find ourselves in the good company of the
19th century French author Gustav Flaubert. The French poet Paul Valery advises us that a
poem is never done and bears continual rework, and to stop working on it is abandonment.
Such preoccupation with detail is common to all endeavors of excellence. So maybe there
is little new here, but in reading this book you will be challenged to take up good disci-
plines that you long ago surrendered to apathy or a desire for spontaneity and just
“responding to change.”
Unfortunately, we usually don’t view such concerns as key cornerstones of the art of
programming. We abandon our code early, not because it is done, but because our value
system focuses more on outward appearance than on the substance of what we deliver.
xxii Foreword
This inattentiveness costs us in the end: A bad penny always shows up. Research, neither in
industry nor in academia, humbles itself to the lowly station of keeping code clean. Back
in my days working in the Bell Labs Software Production Research organization (Produc-
tion, indeed!) we had some back-of-the-envelope findings that suggested that consistent
indentation style was one of the most statistically significant indicators of low bug density.
We want it to be that architecture or programming language or some other high notion
should be the cause of quality; as people whose supposed professionalism owes to the
mastery of tools and lofty design methods, we feel insulted by the value that those factory-
floor machines, the coders, add through the simple consistent application of an indentation
style. To quote my own book of 17 years ago, such style distinguishes excellence from
mere competence. The Japanese worldview understands the crucial value of the everyday
worker and, more so, of the systems of development that owe to the simple, everyday
actions of those workers. Quality is the result of a million selfless acts of care—not just of
any great method that descends from the heavens. That these acts are simple doesn’t mean
that they are simplistic, and it hardly means that they are easy. They are nonetheless the
fabric of greatness and, more so, of beauty, in any human endeavor. To ignore them is not
yet to be fully human.
Of course, I am still an advocate of thinking at broader scope, and particularly of the
value of architectural approaches rooted in deep domain knowledge and software usability.
The book isn’t about that—or, at least, it isn’t obviously about that. This book has a subtler
message whose profoundness should not be underappreciated. It fits with the current saw
of the really code-based people like Peter Sommerlad, Kevlin Henney and Giovanni
Asproni. “The code is the design” and “Simple code” are their mantras. While we must
take care to remember that the interface is the program, and that its structures have much
to say about our program structure, it is crucial to continuously adopt the humble stance
that the design lives in the code. And while rework in the manufacturing metaphor leads to
cost, rework in design leads to value. We should view our code as the beautiful articulation
of noble efforts of design—design as a process, not a static endpoint. It’s in the code that
the architectural metrics of coupling and cohesion play out. If you listen to Larry Constan-
tine describe coupling and cohesion, he speaks in terms of code—not lofty abstract con-
cepts that one might find in UML. Richard Gabriel advises us in his essay, “Abstraction
Descant” that abstraction is evil. Code is anti-evil, and clean code is perhaps divine.
Going back to my little box of Ga-Jol, I think it’s important to note that the Danish
wisdom advises us not just to pay attention to small things, but also to be honest in small
things. This means being honest to the code, honest to our colleagues about the state of our
code and, most of all, being honest with ourselves about our code. Did we Do our Best to
“leave the campground cleaner than we found it”? Did we re-factor our code before check-
ing in? These are not peripheral concerns but concerns that lie squarely in the center of
Agile values. It is a recommended practice in Scrum that re-factoring be part of the con-
cept of “Done.” Neither architecture nor clean code insist on perfection, only on honesty
and doing the best we can. To err is human; to forgive, divine. In Scrum, we make every-
thing visible. We air our dirty laundry. We are honest about the state of our code because
Foreword xxiii
code is never perfect. We become more fully human, more worthy of the divine, and closer
to that greatness in the details.
In our profession, we desperately need all the help we can get. If a clean shop floor
reduces accidents, and well-organized shop tools increase productivity, then I’m all for
them. As for this book, it is the best pragmatic application of Lean principles to software I
have ever seen in print. I expected no less from this practical little group of thinking indi-
viduals that has been striving together for years not only to become better, but also to gift
their knowledge to the industry in works such as you now find in your hands. It leaves the
world a little better than I found it before Uncle Bob sent me the manuscript.
Having completed this exercise in lofty insights, I am off to clean my desk.
James O. Coplien
Mørdrup, Denmark
This page intentionally left blank
Introduction
(c) 2008 Focus Shift
Reproduced with the kind permission of Thom Holwerda.
[Link]
Which door represents your code? Which door represents your team or your company?
Why are we in that room? Is this just a normal code review or have we found a stream of
horrible problems shortly after going live? Are we debugging in a panic, poring over code
that we thought worked? Are customers leaving in droves and managers breathing down
xxv
xxvi Introduction
our necks? How can we make sure we wind up behind the right door when the going gets
tough? The answer is: craftsmanship.
There are two parts to learning craftsmanship: knowledge and work. You must gain
the knowledge of principles, patterns, practices, and heuristics that a craftsman knows, and
you must also grind that knowledge into your fingers, eyes, and gut by working hard and
practicing.
I can teach you the physics of riding a bicycle. Indeed, the classical mathematics is
relatively straightforward. Gravity, friction, angular momentum, center of mass, and so
forth, can be demonstrated with less than a page full of equations. Given those formulae I
could prove to you that bicycle riding is practical and give you all the knowledge you
needed to make it work. And you’d still fall down the first time you climbed on that bike.
Coding is no different. We could write down all the “feel good” principles of clean
code and then trust you to do the work (in other words, let you fall down when you get on
the bike), but then what kind of teachers would that make us, and what kind of student
would that make you?
No. That’s not the way this book is going to work.
Learning to write clean code is hard work. It requires more than just the knowledge of
principles and patterns. You must sweat over it. You must practice it yourself, and watch
yourself fail. You must watch others practice it and fail. You must see them stumble and
retrace their steps. You must see them agonize over decisions and see the price they pay for
making those decisions the wrong way.
Be prepared to work hard while reading this book. This is not a “feel good” book that
you can read on an airplane and finish before you land. This book will make you work, and
work hard. What kind of work will you be doing? You’ll be reading code—lots of code.
And you will be challenged to think about what’s right about that code and what’s wrong
with it. You’ll be asked to follow along as we take modules apart and put them back
together again. This will take time and effort; but we think it will be worth it.
We have divided this book into three parts. The first several chapters describe the prin-
ciples, patterns, and practices of writing clean code. There is quite a bit of code in these
chapters, and they will be challenging to read. They’ll prepare you for the second section
to come. If you put the book down after reading the first section, good luck to you!
The second part of the book is the harder work. It consists of several case studies of
ever-increasing complexity. Each case study is an exercise in cleaning up some code—of
transforming code that has some problems into code that has fewer problems. The detail in
this section is intense. You will have to flip back and forth between the narrative and the
code listings. You will have to analyze and understand the code we are working with and
walk through our reasoning for making each change we make. Set aside some time
because this should take you days.
The third part of this book is the payoff. It is a single chapter containing a list of heu-
ristics and smells gathered while creating the case studies. As we walked through and
cleaned up the code in the case studies, we documented every reason for our actions as a
Introduction xxvii
heuristic or smell. We tried to understand our own reactions to the code we were reading
and changing, and worked hard to capture why we felt what we felt and did what we did.
The result is a knowledge base that desribes the way we think when we write, read, and
clean code.
This knowledge base is of limited value if you don’t do the work of carefully reading
through the case studies in the second part of this book. In those case studies we have care-
fully annotated each change we made with forward references to the heuristics. These for-
ward references appear in square brackets like this: [H22]. This lets you see the context in
which those heuristics were applied and written! It is not the heuristics themselves that are
so valuable, it is the relationship between those heuristics and the discrete decisions we
made while cleaning up the code in the case studies.
To further help you with those relationships, we have placed a cross-reference at the end
of the book that shows the page number for every forward reference. You can use it to look
up each place where a certain heuristic was applied.
If you read the first and third sections and skip over the case studies, then you will
have read yet another “feel good” book about writing good software. But if you take the
time to work through the case studies, following every tiny step, every minute decision—if
you put yourself in our place, and force yourself to think along the same paths that we
thought, then you will gain a much richer understanding of those principles, patterns, prac-
tices, and heuristics. They won’t be “feel good” knowledge any more. They’ll have been
ground into your gut, fingers, and heart. They’ll have become part of you in the same way
that a bicycle becomes an extension of your will when you have mastered how to ride it.
Acknowledgments
Artwork
Thank you to my two artists, Jeniffer Kohnke and Angela Brooks. Jennifer is responsible
for the stunning and creative pictures at the start of each chapter and also for the portraits
of Kent Beck, Ward Cunningham, Bjarne Stroustrup, Ron Jeffries, Grady Booch, Dave
Thomas, Michael Feathers, and myself.
Angela is responsible for the clever pictures that adorn the innards of each chapter.
She has done quite a few pictures for me over the years, including many of the inside pic-
tures in Agile Software Develpment: Principles, Patterns, and Practices. She is also my
firstborn in whom I am well pleased.