As we work, we’ll encounter design issues all the time, whether we’re coding and find something awkward, testing and find something difficult to test, or even if we’re just designing.. C
Trang 1Microsoft Press © 2004
The author of this book demonstrates that you can write well-designed, resilient code
incrementally and safely, while minimizing your investment in speculative up-front design.
Trang 3investment in speculative up-front design As Jeffries builds his sample application, you get firsthand insights into what successful XP development looks like,
complete with real-world challenges such as the
eleventh-hour change order For further practice and study, you can download all the author’s code—
including missteps—so you can see XP and agile
concepts in action and assess how they fit into your own work.
Pair program with an XP master, discovering how to:
Streamline and simplify the software development process
Write cleaner, more expressive code—and weed
Trang 4Conserve resources by planning and reassessing progress as you go
Maintain a sustainable work pace—and avoid
burnout
Step up delivery dates, shipping the most crucial features first
systems developer, he’s been a leader in the XP
movement for more than eight years, speaking at
developer events, writing articles, and editing the
Xprogramming.com Web site.
Trang 5Microsoft Extreme Programming Adventures in C#
Ron Jeffries
PUBLISHED BY Microsoft Press A Division of Microsoft Corporation OneMicrosoft Way Redmond, Washington 98052-6399
Library of Congress Cataloging-in-Publication Data Jeffries, Ron, 1939-Printed and bound in the United States of America
1 2 3 4 5 6 7 8 9 QWE 8 7 6 5 4 3
Distributed in Canada by H.B Fenn and Company Ltd
A CIP catalogue record for this book is available from the British Library.Microsoft Press books are available through booksellers and distributorsworldwide For further information about international editions, contactyour local Microsoft Corporation office or contact Microsoft Press
International directly at fax (425) 936-7329 Visit our Web site at
www.microsoft.com/mspress Send comments to
mspinput@microsoft.com
IntelliSense, Microsoft, Microsoft Press, Visual Basic, Visual Studio, andWindows are either registered trademarks or trademarks of MicrosoftCorporation in the United States and/or other countries Other product
Trang 6The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are
fictitious No association with any real company, organization, product,domain name, e-mail address, logo, person, place, or event is intended
or should be inferred
This book expresses the author’s views and opinions The informationcontained in this book is provided without any express, statutory, or
implied warranties Neither the authors, Microsoft Corporation, nor itsresellers or distributors will be held liable for any damages caused oralleged to be caused either directly or indirectly by this book
Acquisitions Editors: Linda Engelman and Robin Van Steenburgh Developmental and Project Editor: Devon Musgrave
he wonders why he didn’t get more of the money He’s happy, though,that he has had so much fun
Trang 7“Sir! Torpedo Lock! God, there are dozens of them!” The tactical officer’s eyes stared wide at his display This couldn’t be happening “Where
away, Ensign Farber?” Captain Jeffries’ dark penetrating eyes flashed urgency at the young officer He should have announced torpedo location and trajectory without having to be told Seconds counted.
“Thirty by minus 50, range 1-6-0 thousand, 10 thousand kps, sir.” The radial coordinates and incoming velocity vector snapped out with trained precision “A Ferengi vessel just came out of warp behind the torpedoes! Cripes, it must have been firing as it made the transition!”
“Hard over, Helm! Full impulse toward that bogey.”
“Aye, aye, sir! Damn it!” Commander Langr clearly didn’t like that order but immediately turned the ship into the path of the incoming torpedoes and flooded the engines with power The bridge crew grabbed hold of their consoles as the inertial dampers fought to compensate for the
horrific shift in g-forces First Officer Ch’t-Hen locked eyes with the
captain and calmly stated, “Sir, heading into the torpedoes gives us
approximately 7.23 seconds to impact.”
Hen’s.
“Full power, Commander Langr.” Jeffries’ eyes never wavered from Ch’t-Ch’t-Hen continued unabated “I count 42 torpedoes with 12 warheads apiece, each with a yield of 200 megatons The 100.8 gigaton detonation will completely overwhelm our shields Two seconds One ” The crew held their breath for an infinitely long second “Sir,” Ch’t-Hen continued without breaking rhythm, “it would appear that the torpedoes have failed
to detonate.”
Jeffries nodded “Ferengi are too cowardly to arm their torpedoes until they are a safe distance from their ship I think we managed to squeak inside that radius Helm, stay on your course! I want you to miss that Ferengi by inches, Langr, inches! Lieutenant Hill, target our rear phasers
on their warp nacelles Wait until we are two klicks past them, then.”
Trang 8dream By reading this book you’ll learn side-by-side with Ron Jeffries,one of the most talented master programmers in our galaxy You won’tjust learn facts about C#—you’ll learn a master’s principles, patterns, andpractices
Reading this book is as close to having Ron as a one-on-one mentor asit’s possible for print to allow
Are you new to C#? If so, keep a language reference nearby Ron willteach you a lot about C#, but he’s not going to spoon-feed you This isnot a C# tutorial There are many things you are going to have to look upfor yourself However, this book will give you an order in which to lookthose things up Each chapter will lead you to more and more interestingconcepts in C# and to a deeper and deeper understanding of agile
methods Treat this book as a pathway instead of as a reference Do you
already know C#, or Java, or C++? If so, read this book for the skills, theattitudes, the practices, and the thrill of discovery You’ll learn along withRon as he explores C# and NET You’ll gain deep insights into the
From that auspicious start, Ron went on to learn more about software
Trang 91620, and 360 series, the DEC PDP-1 and -7, the SDS/Xerox 940, Sigma
7 and Sigma 9, the 6502, 8080.… In short, he’s been around.
Ron has been fortunate (or devious) enough to work with some of thebest in our industry He’s worked with Ward Cunningham (yes, by readingthis book you’ll have a Ward number of at most 2), Kent Beck, Ken Auer,Bill Wake, Chet Hendrickson, Ann Anderson, Michael Feathers, Jeff
Langr, Michael Hill, Robert Koss, and even—er—me Ron is an
outspoken XPer and a founding signatory to the Manifesto of the AgileAlliance
Ron loves to write code If he has a spare minute, he wants to spend itcoding He’ll go to the Michigan Union to meet a friend, and the two ofthem will crack their laptops and write code together More importantly,
Ron loves to write good code He’s not happy just making the code work Ron wants to make it right And making code right is something that Ron
Jeffries knows better than anyone else Ron takes a rare pride in thecode he produces and in the way he produces it He craves the creation
of magnificence
I first met Ron in 1999 Ron had been doing Extreme Programming (XP)for nearly five years by then He was the first XP coach ever and hadhelped many companies improve their practices Ron drove to my house(in his hatchback Z3) to meet with me to help plan the first XP Immersioncourse I wanted Ron to be one of the instructors This is a decision Ihave never regretted Ron is an outstanding instructor who is deeply
motivated to share his vast wealth of knowledge Ron understands
software with a rare clarity and has the even rarer ability to share thatclarity with others
If you want to learn how to use C# well, if you want your code to be right,
if you want to learn the skills, disciplines, and attitudes of a true master,then you’ve done well to pick up this book Keep reading—you’re in for a
Trang 10Robert C Martin
December, 2003
Trang 11One of the most controversial aspects of Extreme Programming (XP),and of all the “agile” methods, is reduced focus on up-front design Whileagile proponents generally do recommend doing some up-front design,the rapidity with which we turn to programming seems dangerous, evenfoolhardy, to people who don’t understand or who have not yet tried what
we teach
For the past few years, I’ve been experimenting with these ideas I startwith a very simple design idea and implement features in a customer-driven order, using refactoring to keep the design just barely sufficient tothe moment One question I’ve been interested in was whether the codenecessarily becomes brittle, hard to change, and unreliable or whetherthe process seems to be sustainable Another key question has beenwhether more up-front planning and design would give better results, interms of substantially less rework, faster progress, or a better resultingdesign
My findings, for my work, are these:
I can deliver features that the customer wants, at a consistentrate, over the course of the project
I make design improvements all the time, but mechanically theyare more like additions and rearranging things, rather than likerework or redesign or starting over
I can keep the code clean and fit for its purpose, over the course
of the whole project
I invest just as much in good infrastructure as I ever did, perhapseven more, but I make that investment over the course of theproject, not just at the beginning
I deliver more function per unit time, embodied in code that I can
be proud of
This book is a chronicle of a little project done in the style XP
Trang 12language and environment that I had never used before the start of theproject, namely C# and Microsoft Visual Studio NET
Looking back over it now, I’m amazed at how a one-person book projectcan look so much like larger “real-life” projects The project is open toyou I share my thoughts, my mistakes, my little triumphs, and my code,good or bad When I learn a lesson, for the first or hundredth time, I
share it with you (typically in reader aids and sidebars)
For me, the bottom line remains that this approach works for me, and Ican also report that it’s working well for most of the teams all over theworld who are adopting Extreme Programming and agile software
development practices
For you, the opportunity in this book is to see how these practices work inthe hands of an aging geek who is one of the most vocal proponents ofthese ideas You can observe both what works and where I go off therails You can make your own decisions about how to fit the XP/agileideas into your own development bag of tricks
Trang 13My intention in this book is to describe the thought and work practicesthat I use in creating a program and not to present here every line of
code that went into the system You might find value in being able to seeall the code at various states through the project The book’s Web page
at http://www.microsoft.com/mspress/books/6777.asp includes several
snapshots of all the code, taken at various points along the way To
access the code from the book’s Web page, click the Companion Contentlink in the More Information box on the page This will load the
Companion Content Web page, which includes a link to download thesample files
Trang 14To get the most out of this book, you will need the following:
Microsoft Windows (Windows 2000, Windows XP, or WindowsServer 2003)
Microsoft Visual Studio NET 2002 or Visual Studio NET 2003Many of the code samples in the book can also be used with MicrosoftVisual C# NET or with the command-line tools in the Microsoft NETFramework 1.0 (or 1.1) Software Development Kit (SDK) However,because these tools don't have the same capabilities as Visual Studio.NET, the tasks described in the book will be different from your
experience
Trang 15Every effort has been made to ensure the accuracy of the book and thecompanion content Microsoft Press provides corrections for books andcompanion content through the World Wide Web at
http://www.microsoft.com/learning/support/
If you have comments, questions, or ideas regarding the book or thecompanion content, please send them to Microsoft Press by e-mail to
My forebears, betters, and colleagues in the XP and agile community:Ward Cunningham, Kent Beck, Martin Fowler, Alistair Cockburn, JimHighsmith, Andy Hunt and Dave Thomas, Bob Martin, and so many
more
The many people interested in Extreme Programming and agile methodswho have helped me to figure out what I was trying to say, by wadingthrough so many ideas on mailing lists all over the Internet
Trang 16My editors Linda Engleman, without whom this book would not have
happened; Devon Musgrave, without whom it would have appeared to be
in some strange new version of English; my technical editors Lee Holmesand Kyle Cordes; reviewer Dominique Plante; and the many others whohave offered ideas, help, and criticism along the way Jim LeValley atMicrosoft Press, who supported the project from the very beginning Andthe many people behind the scenes at Microsoft, including Carl Diltz, whopaged the book, Julie Kawabata, who created its index, and Joel
Panchot, who created its art Thanks also for the proofreading of SandiResnick at Microsoft and the team at NSightWorks: Joe Armstrong, SteveBoudreault, Catherine Cooker, Kerin Foley, Beth Lew, Katie O'Connell,Dan Shaw, Asa Tomash, and Melissa von Tschudi-Sutton
Trang 17Here are a few more words on the “sound bite” lines, indicated by sb, thatlitter the book, as well as a few on bonus sound bites not found in thebook
Are the objects helping us? (Chapter 31, page 482)
Sometimes as we’re programming along, things go very smoothly It’s as
if all the objects and methods are reaching out, always ready to help us.Other times, it seems that they are hiding, ducking out of the way, fighting
us for every inch If we’re sensitive to these feelings, we can begin tosense when the code we’re working with isn’t as well-designed or as well-structured as it needs to be Do you have to tell some object about tenthings before it will do anything useful? It’s not helping—maybe you canfix it, or find a better helper
Are the tests helping us? (Chapter 31, page 481)
Usually we’ll find that our tests lead us through new areas and protect us
as we change things But sometimes they seem to let us down Are bugscropping up in some areas of the code? Even if we are using “Find a bug,write a test,” we might see continuing weakness in some area of the
code Code weakness can slow us down profoundly It can be worthwhile
to think about and install a new approach to testing that area
Automated tests record our intelligence for later! (Chapter 5, page 65)
Are we having trouble creating some new chunk of code, even using atest-driven approach? Are the tests hard to write or hard to make work?Consider turning attention to the tests for a while Test by using a
different approach, attacking a different corner of the problem or from adifferent angle
If you’re like me, sometimes you write a little patch of code to learn howsome object works and to get a sense of how to use it My habit, formedover many years, is to write a little main program that tries something and
Trang 18it away
I’m trying to train myself to write a TestFixture instead, which has twoadvantages First, using the test-oriented part of my brain seems to help
me learn a little more Second, the test records the use of the object, andthe results, in an easy to find form for later Give it a try—you might like it!
Begin with a test (Chapter 25, page 323)
As programmers, we tend to think in terms of algorithms and solutions
We see a problem and visualize a way to program it And there’s greatjoy in putting some sweet little algorithm together For me, though, thatway often leads to debugging I write a bunch of code, finally get around
situation and don’t elaborate it beyond the current need What we buildneeds always to be robust, well-tested, well- crafted But we can leave offthe bells and whistles, until the customer calls for ringing and hooting
Trang 19Card The names of stories, and perhaps a few words about
them, are written on cards These cards are tokens representingthe requirement, and we can use them to lay out a schedule, tosignify that we have accepted responsibility to implement a
feature, or as part of a display of what’s done and what’s left to
be done But the card is not the full requirement, just a tokencontaining the requirement’s name
Conversation There is an exchange of information between the
Customers, the people who understand the need, and the
Programmers, the people writing the program To build a feature,the programmers need a deep understanding of what needs to
be done This knowledge can be provided by written
requirements specifications as part of the Conversation, but wecall it Conversation to emphasize that understanding comes
unambiguously, in Customer Acceptance Tests Getting thesetests defined and agreed to, you’ll nail down the requirementsquickly The tests will help the programmers know when they aredone and will help them avoid defects Finally, running the testswill give the customer a concrete understanding of how things aregoing Card, conversation, confirmation—don’t do software
without them
Daily builds are for wimps (Extreme Programming, page xxix)
Most teams now realize that weekly or longer build cycles are a disaster
Trang 20it is a team issue, not a blame issue, when the build breaks Stop thewhole assembly line, figure out what went wrong, and fix the root cause.Building many times per day is paradoxically easier than building once.First of all, the changes that can be made in an hour or two don’t deviate
as wildly as those saved up for a whole day or more, so an hourly build ismuch less likely to break Second, if breaking the build is a team issueand we build many times per day, we will get very good at it Those rootcauses of breaks will be discovered and corrected quickly
Design all the time (Chapter 1, page 8)
Design isn’t something that we do just at the beginning of a project orstory or task As we work, we’ll encounter design issues all the time,
whether we’re coding and find something awkward, testing and find
something difficult to test, or even if we’re just designing If we can besensitive to emerging design issues and respond to them immediately,the design will stay closer to good all the time
Don’t fall in love with our own work.
Sometimes we code up something really nifty and we’re pretty proud of it.That’s good—it’s important to practice and to exercise our skills
Sometimes we work really hard on something and finally get it to work.That’s good too— sometimes we have to get things done even if theyaren’t entirely pretty
But both these situations, and others, can sometimes blind us to the factthat there’s a better way to do whatever it is When we feel ourselvesresisting change, defending our code like it was our dearest child, it’smore likely time to let go Don’t fight back Pretend that someone elsewrote that piece of junk, and get on board with seeing what’s wrong with
it and how to make it better Then decide what to do
Trang 21When we test our product, we always try to test it “from end to end.” Wewant to make sure that inputs come in correctly, get processed correctly,and turn into outputs correctly Paradoxically, it always seems that theworst problems occur just beyond the current edges of our testing Whenthis happens, there’s not much we can do but push the ends out a bitfurther I guess we just have to get used to it
Expressing Intention (Chapter 4, page 42)
We always have something in mind as we program, at least I hope we
do When we have finished something, often our intentions changed a bitalong the way, as we learned what the code really wanted to do
Therefore, as we finish up some piece of code, let’s look back at it, and atwhat we were trying to do, and see whether the code expresses thatintention
We have all had that joyful experience of reading some stretch of codeand suddenly seeing what some part of it does: “Look, this bit updates allthe pending requests, then this bit selects one request, then the next bitprocesses that request!” It’s kind of fun to figure out that stuff, but it takestime and energy Let’s change the code to say what it does:
Fake it before you make it Fake it till you make it (Chapter 11, page 146)
In test-driven development, we do best when we cycle very quickly
between writing a test and making it work One way to speed up this
cycle is to send a message to the object under test and, rather than writethe code to return a fully robust answer, merely return a constant Then
Trang 22Find a bug, write a test (Chapter 5, page 58)
We don’t want bugs in our code, right? We find bugs with tests, right? Bywriting tests, we prevent other people from embarrassing us by findingbugs, right? Therefore, if a bug is found, we have missed at least onetest Let’s write it, think about it, and learn from it to write better tests inthe future And, as a useful side effect, when the new tests run, the bug isprobably fixed!
Infrastructure doesn’t please the customer; features do (Chapter
30, page 472)
Of course, we can’t do the program without infrastructure Let’s
recognize, though, that building infrastructure is a necessary evil, andlet’s do it as frugally and incrementally as we possibly can Unused
infrastructure is a waste until it is used Deleted features reduce customerhappiness Put these two facts together and build infrastructure
incrementally, as needed, in support of features
Isolate the unknown.
Often when we’re working on something, we know how to do most of itand there’s just this one part we don’t know how to handle Isolate thatpart, via one of two ways:
We can begin by focusing on that part, writing tests about it,
programming it, and solving it Now, since we understand therest, everything is easy
Or we can pretend that we know the solution, program as if itexists, and get the rest of the program laid out Now we can focus
on the unknown, and often doing what we know has made theunknown more clear
Trang 23“Who broke the build” is a common question but the wrong question Weall broke the build, through omission and commission When a problemoccurs, ask “why,” not “who.” To help with this, we have Chet In the earlydays of Extreme Programming, the team was on a hunt to figure out who
green
Make it work; make it right; make it fast (Chapter 17, page 215)
This might be the oldest advice in computing, except for “Mr Babbage,don’t get your tie in the gears!” I can’t find the original source, but in anycase it’s good advice First make the code get the right answers Don’tspend time honing or optimizing code that doesn’t work yet When it
works, hone it to make it clean Don’t waste time optimizing code that ishard to understand Then— and only then—if a performance test showsthat this code is too slow, make it fast
Outer design should drive inner design, always (Chapter 30, page 473)
There’s not much more irritating than programming with objects that
aren’t helping us (See also Are the objects helping us?) Tests are onegood way to find out how easy or hard an object is to use If it’s hard totest, it’s probably hard to use Plus, it’s often best to program top down, tobetter find out what the objects need to be
Trang 24Programming without thinking…what good is that? (Chapter 30, page 473)
Sometimes it feels like we’re just “cranking out code” by rote, almost
without thinking about it This can be a sign that what we’re doing needs
to be automated in some way, or perhaps we should ask, “Are the objectshelping us?” If you’re programming and not thinking about it, think aboutit
Push a little when something seems too hard (Chapter 17, page 216)
Sometimes I know what I “should” do, but it just seems too hard Whenthat happens, it’s often valuable to push a bit Sometimes I push myself
to start on the difficult-seeming thing Often once I get started, I can keepgoing Other times I push on the idea of why it’s hard Dale Emery refers
to “Resistance as a Resource.” When what we’re doing is resisting us,there can be value in pushing back a bit Of course, there can also bevalue in turning aside and going another way I never said that all thiswould become obvious!
Reflect on how things are going (Chapter 30, page 469)
It’s good to pause frequently to see how we’re doing—another good
reason to drink lots of fluids Sit still for a moment, clear your mind, andpay attention to your body Is it tense, uncomfortable in some way? Isyour neck tight? Are you frowning? Is anything nagging at you? Is thecode trying to tell you something? Are we on the right road, going in theright direction?
Removing duplication is your friend (Chapter 11, page 151)
It’s fascinating how valuable it is to observe and remove duplication in thecode Duplicate code represents some idea that is being used over andover To remove it, we have to clarify that idea and give it a name and aplace to be The code gets better in small, smooth steps Duplication canoccur in space, in time, or in concept Think about it, observe it, and
mindfully remove it
Trang 25(Chapter 6, page 78)
See also Isolate the unknown.
Some very simple refactoring…has done most of the job for us (Chapter 22, page 268)
Sometimes we get to a point where the solution we have been working
on turns out to be wrong Our reaction is often to start over on a newsolution, but there is an alternative and it’s often better Parts of our badsolution might well be pretty good; otherwise, we wouldn’t have beengoing that way Consider refactoring the solution, extracting the good partfrom the bad or the bad from the good In doing so, there’s a good
chance you’ll tease apart the known from the unknown Then just fix thepart that needs it without wasting the good bits or doing them over
Start a new path with something abysmally simple (Chapter 4, page 45)
See also Fake it before you make it Fake it till you make it and What is
the simplest thing that could possibly work? Do the simplest thing that could possibly work.
The story’s not done until the customer tests run (Chapter 6, page 72)
Use Customer Acceptance Tests—the “Confirmation” part of a story—as
a means of communicating, but also as a means of feedback Clearly, wecan’t call a story done until the tests run, but we should strive also to bedone when the tests all run If the tests run but some functionality stillneeds to be added, either the tests are incomplete or we’re working onsomething that the customer doesn’t want If the tests run but there is still
a lot of refactoring or cleanup to do, by all means do it, but try also toneed only a little code to clean up before the code is ready to go
Refactoring works best in small doses all the time, not in big bites Usethe moment when the tests run as a time to see whether your refactoring
is keeping up
Trang 26(Chapter 4, page 45)
Except in rare circumstances, I think I probably write a defect every
twenty lines, or at least every forty Of course, it’s an easy defect andafter only a few console writes or a few moments in the debugger, I’mback on track On the other hand, I can almost always write five lineswithout a defect How many lines should I write between successful
tests?
Two Hats (Chapter 8, page 95)
Kent Beck taught us to think of two hats: a “new functionality” hat and a
“refactoring” hat He told us to wear only one hat at a time, or we wouldlook stupid When we start refactoring in the middle of trying to makesomething work, we seem to make mistakes much more often Add or fixfunctionality when the tests are red Refactor or improve design when thetests are green Are the hats themselves red and green? You decide Myhat is white
We don’t need a testing framework; we need tests (Chapter 6, page 73)
Too often I see teams who have few customer tests because they arewaiting until they (or QA) build a testing framework If we have no tests,
we don’t know whether the program works If we don’t know whether theprogram works, it doesn’t work It’s like driving with your eyes closed untilyou get sunglasses: a really bad idea Don’t wait for a framework—write
a test!
We start new features with large bold strokes We’re intentionally building from rough toward smooth (Chapter 4, page 47)
You don’t build fine furniture by taking triple-zero sandpaper to the
nearest tree The sequence is more like chain saw, band saw, circularsaw, hand saw, coarse sandpaper, and finally the triple-aught Considercoding the same way, first getting the big bits right and then refining andrefining until everything is fitted just right I think you’ll save a lot of time,instead of polishing the wrong bits
Trang 27What is the simplest thing that could possibly work? Do the
simplest thing that could possibly work (Chapter 28, page 408)
Often our first approach to a new problem is overly complex We don’tfully understand what we’re up against, and we respond by figuring out abig solution or by fumbling around for hours with an ill-conceived idea.When he hears someone imagining a solution that may be too complex,Kent Beck likes to ask, “What is the simplest thing that could possiblywork?” When we look at the problem this way, we often see a simplerapproach that will get us started, or perhaps, even see us through
For the past few years, in my own code, I’ve been taking this idea a stepfurther: I ask myself what the simplest thing is that could possibly work,and then I do it I don’t expect these solutions to hold up till the end of theapplication, although often they do But because I try always to keep theshape of the code good, the simple solution is easy to improve later.Meanwhile, I’m free to concentrate on the whole problem, by realizingthis detail in a simple, albeit temporary way
YAGNI—You Aren’t Gonna Need It (Chapter 14, page 192)
We have all been there: We’re coding away on something and we seethe possibility for a neat generalization or a nifty feature We don’t reallyneed it right now, but “We’re gonna need it—might as well do it now.”Extreme Programming suggests that “you aren’t gonna need it,” but notbecause you aren’t going to need it Sometimes you will need it We justautomatically deny that “we’re gonna need it” for a moment, because theissue really isn’t the future—the issue is now!
We don’t need it now If we write it now, it will lie unused for some period
of time, until we do need it, if we ever do Leaving aside whether we everneed it, and leaving aside whether it’s just right for what we do finally
need, face this: our investment of time in that neat feature is wasted until
that future day when we put it into use, if in fact we ever do Let’s insteaduse our time now to make our customer happy, with another feature thatshe actually wants That’s not waste—that’s production
Trang 28“We figure the code we’ll put in now will be the right code later?” I ask.You assure me that it will
“So, if we wait, we’ll just have to put that same code in there after all?”
“Yes,” you tell me
“Well,” I ask, “if it’s the same code, why will it be harder later than it isnow?” You glare at me for a while and then try, “But I know how to do itnow, and I’ll have to figure it out again later.”
“So, the code we have now is hard to understand? Maybe we should focus on that instead of this new feature?”
Well, probably at this point you kill me, which makes me glad this is abook and not a meeting But my point remains: it should not be cheapernow than later, and, if it is, we should address that issue, not the newfeature
Now of all the points in this book, this may be the hardest to accept, so in
a way I’m glad it’s at the end of this list I hope you believe me, but I’mnot asking you to take it on faith Instead, I’m asking this: When you haveone of those ideas and you decide to go ahead and do it, pay attention towhat happens How long does it take to do; does it get used; how long is
it until it is used; how close to right is it when it does get used; and howhard does it look to do if you had to do it at that point?
And sometimes, when you have one of those ideas, make note of it, butdon’t put it in See whether the time comes when you do need to do itand how hard it is to do at that later time Adjust your balance as yourown experience dictates, and maybe drop me a note about what youlearned
Trang 29In this second introductory chapter, we’ll take a brief look at the XPvalues and practices as background for how we approach things in therest of the book
Trang 30While this isn’t a book about Extreme Programming, it is a book aboutwhat an XP practitioner does Some of what we’ll see here is right out ofthe XP body of knowledge, and some comes from the general knowledge
we all build up over the years—in my case, over many years
Team members on XP projects are expected to do the same: to use thespecialized XP values and practices and to blend these thoughtfully withall the other skills that they have And if that isn’t enough, we’re expected
to learn and apply new skills as we go That, in fact, is the topic of this
book: how we can build useful software in a situation where we have a lot
to learn.
Trang 31Kent Beck, the founder of the Extreme Programming movement, saysthat “XP is a community of software development practice based on
values of simplicity, communication, feedback, and courage.” Let’s lookbriefly at these values and how they influence our approach to projects.After a look at the values, we’ll examine XP’s fundamental practices
Simplicity
Some approaches to software development are quite complex, with manyphases, rituals, plans, handoffs, and steps XP, in contrast, is focused onbeing “the simplest process that could possibly work.” There are no
required phases, documents, or steps Your project situation may wellrequire you to add in some of these complexity-adding elements, and if
so, you must do them and do them well To borrow the words of Einstein,
an XP project should be “as simple as possible, but no simpler.”
Communication
Most projects have more than one person involved, and communicationamong these individuals is critical to project success, whether they aredevelopers or some other kind of stakeholders Extreme Programmingemphasizes face-to-face, person-to-person communication We makethis emphasis partly in the spirit of simplicity, but mostly because two-wayperson-to-person communication is far more effective for reaching
understanding and agreement than are colder forms of communicationsuch as writing You may find it desirable to document a joint
understanding or agreement after the fact Attaining that common view ismost important, and that is far better done face to face when possible
Feedback
Complex efforts such as software projects work far better if we steer
them frequently Steering is a process of observing where we are andwhere we are heading, and making frequent adjustments XP is full ofpractices that provide feedback Face-to-face communication, already
Trang 32communication is going XP also uses extensive automated testing toprovide feedback on how well the software is progressing, frequent
delivery of running tested software to users to find out how well we aremeeting their real needs, and short cycles of development to let us
assess progress and accurately predict delivery time and contents
Courage
Because it is rich in communication and feedback, XP fills project
stakeholders with courage and confidence about how things are going.But XP also calls for courage in the first place: the courage to do simplethings, to communicate openly and frequently, and to trust our fellowstakeholders on the project
This is not blind courage; it is informed courage, created by simple
feedback mechanisms and clear, open communication Assessing ourlevel of courage is a valuable flag that gives us feedback on how well weare performing our practices and how well we are living up to our values
The Values in Concert
As an XP team goes forward, it strives always to make decisions in thelight of these values Team members adjust their practices, always, tohave the best blend of simplicity, communication, feedback, and courage
Trang 33Building on the values of simplicity, communication, feedback, and
courage, Extreme Programming is characterized by about a dozen keypractices, 13 in the form I use to describe them I’ll describe the practicesand then discuss how they are best used and how they “characterize” theExtreme Programming process
Whole Team
The Whole Team practice calls for all the stakeholders—developers,managers, customers, and users—to form a single team The practicecalls for the team to work together and to be together psychologically andeven physically The ideal situation is to have the whole team together, inone room, to do their work.[1]
The Whole Team practice was originally called “On-Site Customer” toreflect the special importance of a tight connection between the peoplewho need the software, customers and users in the XP “Customer” role,and those developing it, developers and managers, whom we call
“Programmers.” When customers and programmers are together,
information flows freely and rapidly Perhaps even more important,
working together engenders trust and cooperation between these twohalves of one project
This practice, as you can see, supports the values of simplicity,
communication, and feedback It enables the team to use conversationinstead of needing so much written material, and because the team
by the Whole Team, never by a single individual either inside or outside
Trang 34understand time and money budgets, and programmers understand how
to build things and how long it will take
The XP “Release Plan” lays out a picture of the whole project It looks atall the known requirements in sufficient detail to associate an estimatewith each desired feature, or “story,” as we call the features With
estimates in hand, customers and managers can put together the bestpossible schedule given priority and budget This plan is, of course,
subject to revision as the whole team learns more about all the variables:feature definitions, priorities, actual costs, and changing budgets An XPRelease Plan can give an increasingly accurate picture of what is reallygoing to happen Wise teams update their Release Plans very frequently.The XP “Iteration Plan” plans the next iteration XP teams develop
software in short time-boxed periods called iterations, typically spanningone or two weeks In each iteration, the team plans, builds, and deliverstested new features to the customer Yes, features are delivered startingwith the very first iteration There’s no “three months to set up the
framework” in XP, and just how we go about delivering with the first
iteration is the real subject of this book
At the beginning of each iteration, the Iteration Plan is produced At first,
it can be difficult to know how much we can get done in an iteration, butbecause we repeat the planning process every week or two, we quicklyget quite good at it The customer, based on the programmers’ estimates
of cost and on the team’s observed speed of building features, selectsthe feature stories to be built The team puts together a simple plan to getthese stories done and then builds, tests, and delivers the software
These XP planning practices are quite simple They focus on
communication of requirements stories and on feedback about the speedand quality of our implementation In addition, the customers get goodfeedback on the quality of their decisions, by seeing the actual results oftheir requests in tested, running software
Small Releases
Trang 35frequently as possible If an XP project were to run for a year, we wouldlike to ship production versions four or more times during that period.This practice provides important feedback to stakeholders on how wellthe team is progressing Placing the product in real users’ hands alsoprovides important feedback on the quality of requirements stories and
on priority decisions
Customer Acceptance Tests
Although requirements stories are written on cards to serve as planningtokens, and although stories are explained in many conversations
between programmers and the on-site customers, requirements in XPhave a third critical component: confirmation The customer confirms thatevery story is correctly understood and implemented by defining one ormore automated “Customer Acceptance Tests” (also referred to as
“customer tests” throughout this book) Let’s underline these points An
XP story includes three aspects: card, conversation, and confirmation.And the story is done when the Customer Acceptance Tests run
This practice provides important feedback to the customers about thequality of the team’s work—and important feedback about the quality ofthe customers’ own tests The customer tests communicate and
document the precise requirements in an unambiguous and verifiableway Seeing the Customer Acceptance Tests coming on line and
continuing to work gives the entire team confidence that things are goingwell and provides the courage to continue
Simple Design
As a new program comes into being, it starts out small and grows overtime We want the design of the program to be good always, and we
observe that a small program’s good design can and should be muchsimpler than that of a larger program Because we are building the
program incrementally, shipping new and improved versions every couple
Trang 36to the program The result is that our design investment is spread overthe whole life of the project, rather than loaded at the front Because ofthis, we can spread the delivery of features over the life of the project aswell, instead of loading feature delivery towards the end We can evendeliver the most important features early in the project lifetime This
practice improves the return on the project investment, and it gives ourstakeholders great feedback and courage about the project We focus onkeeping the program as simple as possible but no simpler We use therapid feedback of XP’s short iterations to improve the design
This book is about this process It explores how we can begin a project knowing very little, begin with a simple design, and keep our design good
as we grow the program.
Pair Programming
Extreme Programmers write their production code with two programmerssitting side by side at the same machine This practice provides
immediate code review for every line of code, it improves the design
every step of the way, it helps us maintain energy and momentum, and ithelps us maintain the discipline to work in the most effective way weknow how
Most programmers have worked together on hard or interesting
problems, and usually they find it productive and beneficial ExtremeProgrammers work together all the time and gain the benefits all the time.The practice of pair programming provides immediate feedback on thequality of our work It helps us communicate the design ideas, and it
helps us upgrade our skills through sharing It gives us courage to work
on parts of the code we might otherwise be afraid to touch
In this book, which is mostly a one-person effort, I didn’t always get to pair program This means you’ll get a clear look via my efforts in this book at the effects of working with someone else versus working alone.
Trang 37Because we are growing the program as we go, because we are
committed to improving the design, and because we must ship workingsoftware so frequently, we need great confidence that our new code, andour design changes, work as we intended them to We cannot afford tohave some design change break existing functionality or slow down theadding of new features
Extreme Programmers accomplish this using “Programmer Unit Tests”(also referred to as “programmer tests” throughout this book), which wewrite as we go We write most of the tests one at a time, immediatelybefore adding the feature being tested When, as inevitably happens, we
do find a defect after the fact, we write new tests that first show that thedefect exists and that then confirm we have the problem fixed The
existence of this growing family of tests helps us communicate what thecode is supposed to do and how to use it, and it gives us feedback as towhether the code does its job correctly The automated tests give usconcrete feedback, showing that our changes haven’t broken anything,and they give us the courage to make the changes needed to keep theprogram alive and growing
In this book, you’ll see how we write these tests and how they give us courage You’ll also see what happens when we slip and don’t write all the tests we should!
Design Improvement
If we’re going to start small and simple and to grow the program whilekeeping its design good, we must improve the design as we go ExtremeProgrammers do design improvement using “refactoring,” a highly
Trang 38The refactoring practice supports the simplicity of the design and
improves the ability of the code to communicate its design and intent.Continuous refactoring on an XP project is safe because we have ourextensive automated tests to give us feedback on our changes and togives us the courage to continue
In this book, you’ll see our simple program’s design improve through refactoring, and you’ll get a sense for the power of the technique and the pitfalls in its use.
Supporting Practices
The eight practices described so far include the four that help with thecustomer/programmer interface: Whole Team, Planning Game, SmallReleases, and Customer Acceptance Tests I call these the “Circle ofLife.” The other four practices make up the central programming cycle,which might be called the “Circle of Code”: Simple Design, Pair
Programming, Test-Driven Development, and Design Improvement
There are five more supporting practices that we need to consider briefly
XP teams practice Continuous Integration The program is always
integrated, always ready to go XP teams say that sbdaily builds are forwimps (Througout this book, the sb superscript indicates the beginning
of what I’m calling a “sound bite.” See the “Sound Bites” chapter at theback of the book for more on these.) The best XP teams, even quite largeones, integrate and build the entire system many times per day Thispractice provides feedback on the quality of our work, and ensures that
we will communicate frequently about what we’re doing
Extreme Programmers practice Team Code Ownership Any pair of
programmers is empowered to improve any code at any time This
practice is safe because of our many tests and easy to do because wepair program, learning new areas of the system all the time The practiceprovides a simple way to put resources where they’re needed, provides a
Trang 39XP teams evolve a Coding Standard Because we work together all thetime, a standard is inevitable We’ll have to agree on a few things, likewhere to put the curly braces, but most of the standard emerges as anatural result of working in pairs and owning all the code as a team Thecoding standard adds simplicity to our process by allowing flexibility and
by settling many details It improves our ability to give feedback by
keeping the form of all code familiar It helps us communicate through thecode, and it gives us courage to contribute to any area needing our help
XP teams use a Metaphor or System of Names to provide a common
language for talking about the design of the program Often a simplemetaphor can help us focus on how the system works: “It’s like a swarm
of bees that go out on the Web and bring information back to the hive.”
Or “It’s like a manufacturing line that manufactures checks instead ofcars.” Even if we don’t have an evocative metaphor, we develop a
common terminology that helps us communicate quickly and effectively
XP teams work at a Sustainable Pace We do not kick way back
sometimes and work massive overtime at other times We strive to go asfast as possible and no faster While we’ll certainly put in extra hours in
an emergency, we are very sensitive to the fact that an over-tired team is
a stupid team and stupefied programmers write defective programs
Worse yet, they write those defective programs slowly! We work hard,rest well, and come back to work refreshed Sustainable Pace is not alicense to slack off; it is a demand that we always make our best possibleforward speed This practice provides consistent velocity feedback, whichcommunicates how we’re doing to our customers and other stakeholders
It requires that we know what our best pace is and that we have the
courage to stick to it
[1]When we say “ideal,” we mean it Recent studies at the University ofMichigan found that teams work ing physically together were two times
as effective as those working apart
Trang 40People often ask us if it’s still XP if we don’t have a customer with us, orwork in cubes instead of together, or don’t pair program, or don’t writemany tests It’s natural to ask this question, but in fact it isn’t that helpful.Software development is a complex business, and it requires all the skill
we can bring to bear and all the good practices we know The ExtremeProgramming practices represent important skills in software
development They are rich—they represent many skills, not just a
dozen They work together in ways that are fairly obvious, like the waythat testing supports improving the design without breaking things Theyalso work together in subtle ways, ways that you’ll recognize only whenyou encounter them People who learn and use all the practices,
together, all the time, often report that the development experience hasbeen one of the best of their lives
My advice to you is to try all the practices, mindfully, until you are skilledwith them Use them in all the combinations you can, and integrate themfully into your skill set Eventually, it won’t matter then whether you’re
“doing XP” or not You’ll be better equipped to do the best work of whichyou are capable in a style that is what it should be: a style all your own