Tải bản đầy đủ (.pdf) (856 trang)

Ms press extreme programming adventures in c sharp

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.64 MB, 856 trang )

ExtremeProgrammingAdventuresinC#
ISBN:0735619492
byRonJeffries
MicrosoftPress©2004
Theauthorofthisbookdemonstratesthatyou
canwritewell-designed,resilientcode
incrementallyandsafely,whileminimizing
yourinvestmentinspeculativeup-front
design.
TableofContents
MicrosoftExtremeProgrammingAdventuresinC#
Foreword
Introduction
ExtremeProgramming
Chapter1 - XMLNotepadStories
Chapter2 - TestingwithNUnit
Chapter3 - APressingMatter
Chapter4 - ExtractingtheModel
Chapter5 - ExpressingIdeas
Chapter6 - TheFirstCustomerAcceptanceTest
Chapter7 - WartsandAll
Chapter8 - TheInputCommandObject
Chapter9 - StoryOneIsDone!
Chapter10 - FindaBug,WriteaTest
Chapter11 - AddingtheSectionTag,PartI
Chapter12 - AddingtheSectionTag,PartII
Chapter13 - DiscoveringtheMenu
Chapter14 - Don’tTryThisatHome


Chapter15 - ClimbingOutoftheRatHole


Chapter16 - Addingthe
Tag
Chapter17 - HowDoWeDoaTestThatWeCan’tDo?
Chapter18 - ASimpleFeatureTeachesSomeLessons
Chapter19 - DarkCloudsontheHorizon
Chapter20 - FinishingtheShift+EnterStory
Chapter21 - SomeThingsWeOughttoDo
Chapter22 - TheDelegatefromTroy
Chapter23 - PlanningInterlude
Chapter24 - FileSaveandLoad
Chapter25 - TaggingAlong
Chapter26 - MenuArrays
Chapter27 - DisplayingtheArticle
Chapter28 - OhNo!Undo!
Chapter29 - TheFinalOptimizedUndo
Chapter30 - TheLongDarkTeatimeoftheSoul
Chapter31 - ProjectRetrospective
Bibliography
Index
ListofLessons


BackCover
SeeeXtremeProgramming(XP)inactionatthehands
ofanXPmater—andlearnMicrosoft.NETandC#
programmingintheprocess!Inthisfast-paced,handsonexposition,RonJeffries—oneoftheleadingvoices
andpractitionerintheXPcommunity—demonstrates
thatyoucanwritewell-designed,resilientcode
incrementallyandsafely,whileminimizingyour
investmentinspeculativeup-frontdesign.AsJeffries
buildshissampleapplication,yougetfirsthandinsights

intowhatsuccessfulXPdevelopmentlookslike,
completewithreal-worldchallengessuchasthe
eleventh-hourchangeorder.Forfurtherpracticeand
study,youcandownloadalltheauthor’scode—
includingmissteps—soyoucanseeXPandagile
conceptsinactionandassesshowtheyfitintoyour
ownwork.
PairprogramwithanXPmaster,discoveringhowto:
Streamlineandsimplifythesoftwaredevelopment
process
WorkmoreeffectivelyaspartofanXP
developmentteam
Reducemisstepsbydesigning,testing,and
refiningcodeinincrements
Receiveclearerspecificationsandfeedbackfrom
customers
Writecleaner,moreexpressivecode—andweed


outmorebugs
Conserveresourcesbyplanningandreassessing
progressasyougo
Maintainasustainableworkpace—andavoid
burnout
Stepupdeliverydates,shippingthemostcrucial
featuresfirst
Improvecustomersatisfaction!
AbouttheAuthor
RonJeffrieswastheonsitecoachfortheoriginal
eXtremeProgrammingsoftwaredevelopmentproject.

HealsohelpedplanandteachthefirstXPimmersion
course.Anindependentconsultantandveteran
systemsdeveloper,he’sbeenaleaderintheXP
movementformorethaneightyears,speakingat
developerevents,writingarticles,andeditingthe
Xprogramming.comWebsite.


MicrosoftExtremeProgrammingAdventuresin
C#
RonJeffries
PUBLISHEDBYMicrosoftPressADivisionofMicrosoftCorporationOne
MicrosoftWayRedmond,Washington98052-6399
Copyright©2004byRonaldE.Jeffries
Allrightsreserved.Nopartofthecontentsofthisbookmaybe
reproducedortransmittedinanyformorbyanymeanswithoutthe
writtenpermissionofthepublisher.
LibraryofCongressCataloging-in-PublicationDataJeffries,Ron,1939ExtremeProgrammingAdventuresinC#/RonJeffries.p.cm.Includes
index.ISBN0-7356-1949-21.Computersoftware--Development.2.
eXtremeprogramming.3.C#(Computerprogramlanguage.)I.Title.
QA76.76D47J4372004005.1'1--dc222003068645
PrintedandboundintheUnitedStatesofAmerica.
123456789QWE876543
DistributedinCanadabyH.B.FennandCompanyLtd.
ACIPcataloguerecordforthisbookisavailablefromtheBritishLibrary.
MicrosoftPressbooksareavailablethroughbooksellersanddistributors
worldwide.Forfurtherinformationaboutinternationaleditions,contact
yourlocalMicrosoftCorporationofficeorcontactMicrosoftPress
Internationaldirectlyatfax(425)936-7329.VisitourWebsiteat
www.microsoft.com/mspress.Sendcommentsto


IntelliSense,Microsoft,MicrosoftPress,VisualBasic,VisualStudio,and
WindowsareeitherregisteredtrademarksortrademarksofMicrosoft
CorporationintheUnitedStatesand/orothercountries.Otherproduct


andcompanynamesmentionedhereinmaybethetrademarksoftheir
respectiveowners.
Theexamplecompanies,organizations,products,domainnames,e-mail
addresses,logos,people,places,andeventsdepictedhereinare
fictitious.Noassociationwithanyrealcompany,organization,product,
domainname,e-mailaddress,logo,person,place,oreventisintended
orshouldbeinferred.
Thisbookexpressestheauthor’sviewsandopinions.Theinformation
containedinthisbookisprovidedwithoutanyexpress,statutory,or
impliedwarranties.Neithertheauthors,MicrosoftCorporation,norits
resellersordistributorswillbeheldliableforanydamagescausedor
allegedtobecausedeitherdirectlyorindirectlybythisbook.
AcquisitionsEditors:LindaEngelmanandRobinVanSteenburgh
DevelopmentalandProjectEditor:DevonMusgrave
Indexer:JulieKawabata
InteriorArtist:JoelPanchot
DesktopPublisher:CarlDiltz
BodyPartNo.X10-25681
ToKent—withoutwhomnoneofthiswouldhavehappened.
ToRicia—withoutwhomnoneofthiswouldhavemattered.
RonJeffries
RonJeffrieshasbeenwritingsoftwarelongerthanmostpeopleinthe
professionhavebeenalive.Inspiteofacademicdegreesandhelpfrom
someofthebestsoftwaredevelopersintheworld,hehaslearnedmore

fromhismistakes,throughhavingmadesomanyofthem.Ron’steams
haveshippedoverhalfabilliondollarsworthofcommercialsoftware,and
hewonderswhyhedidn’tgetmoreofthemoney.He’shappy,though,
thathehashadsomuchfun.


Foreword
“Sir!TorpedoLock!God,therearedozensofthem!”Thetacticalofficer’s
eyesstaredwideathisdisplay.Thiscouldn’tbehappening.“Where
away,EnsignFarber?”CaptainJeffries’darkpenetratingeyesflashed
urgencyattheyoungofficer.Heshouldhaveannouncedtorpedolocation
andtrajectorywithouthavingtobetold.Secondscounted.
“Thirtybyminus50,range1-6-0thousand,10thousandkps,sir.”The
radialcoordinatesandincomingvelocityvectorsnappedoutwithtrained
precision.“AFerengivesseljustcameoutofwarpbehindthetorpedoes!
Cripes,itmusthavebeenfiringasitmadethetransition!”
“Hardover,Helm!Fullimpulsetowardthatbogey.”
“Aye,aye,sir!Damnit!”CommanderLangrclearlydidn’tlikethatorder
butimmediatelyturnedtheshipintothepathoftheincomingtorpedoes
andfloodedtheengineswithpower.Thebridgecrewgrabbedholdof
theirconsolesastheinertialdampersfoughttocompensateforthe
horrificshifting-forces.FirstOfficerCh’t-Henlockedeyeswiththe
captainandcalmlystated,“Sir,headingintothetorpedoesgivesus
approximately7.23secondstoimpact.”
“Fullpower,CommanderLangr.”Jeffries’eyesneverwaveredfromCh’tHen’s.
Ch’t-Hencontinuedunabated.“Icount42torpedoeswith12warheads
apiece,eachwithayieldof200megatons.The100.8gigatondetonation
willcompletelyoverwhelmourshields...Twoseconds...One...”Thecrew
heldtheirbreathforaninfinitelylongsecond.“Sir,”Ch’t-Hencontinued
withoutbreakingrhythm,“itwouldappearthatthetorpedoeshavefailed

todetonate.”
Jeffriesnodded.“Ferengiaretoocowardlytoarmtheirtorpedoesuntil
theyareasafedistancefromtheirship.Ithinkwemanagedtosqueak
insidethatradius.Helm,stayonyourcourse!Iwantyoutomissthat
Ferengibyinches,Langr,inches!LieutenantHill,targetourrearphasers
ontheirwarpnacelles.Waituntilwearetwoklickspastthem,then.”


OK,nowthatIhaveyourattention,Iwantyoutoknowthatyouhave
chosentherightbook.Ipresumeyoupickeditupbecauseyouwantedto
learnsomethingaboutC#andagilemethods.Ifso,don’tputitdownnow.
Thisbookwilltakeyouonanadventurethatiseveryprogrammer’s
dream.Byreadingthisbookyou’lllearnside-by-sidewithRonJeffries,
oneofthemosttalentedmasterprogrammersinourgalaxy.Youwon’t
justlearnfactsaboutC#—you’lllearnamaster’sprinciples,patterns,and
practices.
Inthisbook,Ronpairprogramswithyou.Asyoureadit,youwillfeelthat
youaresittingnexttohim,watchinghim—evenhelpinghim—towriteC#
code.You’llreadhisthoughts,hisfears,hiscomplaints,andhis
rejoicings.You’lllaughwithhim,andyou’llgetmadathim.You’ll
participateinhismistakesandsuccesses.You’llagreeanddisagreewith
him.You’llarguewithhim,andsomeofthoseargumentsyou’llwin.
ReadingthisbookisasclosetohavingRonasaone-on-onementoras
it’spossibleforprinttoallow.
AreyounewtoC#?Ifso,keepalanguagereferencenearby.Ronwill
teachyoualotaboutC#,buthe’snotgoingtospoon-feedyou.Thisis
notaC#tutorial.Therearemanythingsyouaregoingtohavetolookup
foryourself.However,thisbookwillgiveyouanorderinwhichtolook
thosethingsup.Eachchapterwillleadyoutomoreandmoreinteresting
conceptsinC#andtoadeeperanddeeperunderstandingofagile

methods.Treatthisbookasapathwayinsteadofasareference.Doyou
alreadyknowC#,orJava,orC++?Ifso,readthisbookfortheskills,the
attitudes,thepractices,andthethrillofdiscovery.You’lllearnalongwith
RonasheexploresC#and.NET.You’llgaindeepinsightsintothe
thoughtprocesses,personalvalues,andsubtlegesturesofamaster.
RonJeffriesstartedhisprogrammingadventuresin1961(beforethe
BeatlesappearedonEdSullivan!)attheageof21.Throughanaccident
offortune,hefoundhimselfworkingsummersatStrategicAirCommand
(inahardenedundergroundinstallation)andwasabletoplaywiththeir
computersystems.Helearnedprogrammingfromsomeofthebrightest
folkswhohadbeenchargedwithoursecurity,andhecouldapplythat
learningwithsomeofthebestandmostpowerfultoolsinexistence.
Fromthatauspiciousstart,Ronwentontolearnmoreaboutsoftware


thantherewastoknowatthetime.Hewrotecompilers,databases,tax
systems,payrollsystems,obscuremathematicalprocessors,business
systems,multi-programmingoperatingsystems,etc,etc.He’sworkedin
APL,Basic,C,C++,C#,CommercialTranslator,Delphi,Fortran,IPL-V,
LISP,Logo,Pascal,Prolog,Smalltalk,Snobol,IBM704,7090,1401,
1620,and360series,theDECPDP-1and-7,theSDS/Xerox940,Sigma
7andSigma9,the6502,8080.…Inshort,he’sbeenaround.
Ronhasbeenfortunate(ordevious)enoughtoworkwithsomeofthe
bestinourindustry.He’sworkedwithWardCunningham(yes,byreading
thisbookyou’llhaveaWardnumberofatmost2),KentBeck,KenAuer,
BillWake,ChetHendrickson,AnnAnderson,MichaelFeathers,Jeff
Langr,MichaelHill,RobertKoss,andeven—er—me.Ronisan
outspokenXPerandafoundingsignatorytotheManifestooftheAgile
Alliance.
Ronlovestowritecode.Ifhehasaspareminute,hewantstospendit

coding.He’llgototheMichiganUniontomeetafriend,andthetwoof
themwillcracktheirlaptopsandwritecodetogether.Moreimportantly,
Ronlovestowritegoodcode.He’snothappyjustmakingthecodework.
Ronwantstomakeitright.AndmakingcoderightissomethingthatRon
Jeffriesknowsbetterthananyoneelse.Rontakesarareprideinthe
codeheproducesandinthewayheproducesit.Hecravesthecreation
ofmagnificence.
IfirstmetRonin1999.RonhadbeendoingExtremeProgramming(XP)
fornearlyfiveyearsbythen.HewasthefirstXPcoacheverandhad
helpedmanycompaniesimprovetheirpractices.Rondrovetomyhouse
(inhishatchbackZ3)tomeetwithmetohelpplanthefirstXPImmersion
course.IwantedRontobeoneoftheinstructors.ThisisadecisionI
haveneverregretted.Ronisanoutstandinginstructorwhoisdeeply
motivatedtosharehisvastwealthofknowledge.Ronunderstands
softwarewitharareclarityandhastheevenrarerabilitytosharethat
claritywithothers.
IfyouwanttolearnhowtouseC#well,ifyouwantyourcodetoberight,
ifyouwanttolearntheskills,disciplines,andattitudesofatruemaster,
thenyou’vedonewelltopickupthisbook.Keepreading—you’reinfora


wildadventure.You’llboldlygowhereyou’venevergonebefore.
RobertC.Martin
December,2003


Introduction
OneofthemostcontroversialaspectsofExtremeProgramming(XP),
andofallthe“agile”methods,isreducedfocusonup-frontdesign.While
agileproponentsgenerallydorecommenddoingsomeup-frontdesign,

therapiditywithwhichweturntoprogrammingseemsdangerous,even
foolhardy,topeoplewhodon’tunderstandorwhohavenotyettriedwhat
weteach.
Forthepastfewyears,I’vebeenexperimentingwiththeseideas.Istart
withaverysimpledesignideaandimplementfeaturesinacustomerdrivenorder,usingrefactoringtokeepthedesignjustbarelysufficientto
themoment.OnequestionI’vebeeninterestedinwaswhetherthecode
necessarilybecomesbrittle,hardtochange,andunreliableorwhether
theprocessseemstobesustainable.Anotherkeyquestionhasbeen
whethermoreup-frontplanninganddesignwouldgivebetterresults,in
termsofsubstantiallylessrework,fasterprogress,orabetterresulting
design.
Myfindings,formywork,arethese:
Icandeliverfeaturesthatthecustomerwants,ataconsistent
rate,overthecourseoftheproject.
Imakedesignimprovementsallthetime,butmechanicallythey
aremorelikeadditionsandrearrangingthings,ratherthanlike
reworkorredesignorstartingover.
Icankeepthecodecleanandfitforitspurpose,overthecourse
ofthewholeproject.
IinvestjustasmuchingoodinfrastructureasIeverdid,perhaps
evenmore,butImakethatinvestmentoverthecourseofthe
project,notjustatthebeginning.
Idelivermorefunctionperunittime,embodiedincodethatIcan
beproudof.
ThisbookisachronicleofalittleprojectdoneinthestyleXP


recommends,insofarasI’mcapableofdoingwhatIteach.Theproject
includesmanyofthethingsthatbefallrealprojects:peopleleavethe
projectandcomeback,newpeoplecomeinforawhile,keypeopleget

sick,hardproblemscropup,andsoon.Weevengetadifficult“surprise”
requirement.Tomakeitevenmoredifficult,Ichoseaprogramming
languageandenvironmentthatIhadneverusedbeforethestartofthe
project,namelyC#andMicrosoftVisualStudio.NET.
Lookingbackoveritnow,I’mamazedathowaone-personbookproject
canlooksomuchlikelarger“real-life”projects.Theprojectisopento
you.Isharemythoughts,mymistakes,mylittletriumphs,andmycode,
goodorbad.WhenIlearnalesson,forthefirstorhundredthtime,I
shareitwithyou(typicallyinreaderaidsandsidebars).
Forme,thebottomlineremainsthatthisapproachworksforme,andI
canalsoreportthatit’sworkingwellformostoftheteamsalloverthe
worldwhoareadoptingExtremeProgrammingandagilesoftware
developmentpractices.
Foryou,theopportunityinthisbookistoseehowthesepracticesworkin
thehandsofanaginggeekwhoisoneofthemostvocalproponentsof
theseideas.YoucanobservebothwhatworksandwhereIgooffthe
rails.YoucanmakeyourowndecisionsabouthowtofittheXP/agile
ideasintoyourowndevelopmentbagoftricks.


CodeontheCompanionWebSite
Myintentioninthisbookistodescribethethoughtandworkpractices
thatIuseincreatingaprogramandnottopresenthereeverylineof
codethatwentintothesystem.Youmightfindvalueinbeingabletosee
allthecodeatvariousstatesthroughtheproject.Thebook’sWebpage
atincludesseveral
snapshotsofallthecode,takenatvariouspointsalongtheway.To
accessthecodefromthebook’sWebpage,clicktheCompanionContent
linkintheMoreInformationboxonthepage.Thiswillloadthe
CompanionContentWebpage,whichincludesalinktodownloadthe

samplefiles.


SystemRequirements
Togetthemostoutofthisbook,youwillneedthefollowing:
MicrosoftWindows(Windows2000,WindowsXP,orWindows
Server2003)
MicrosoftVisualStudio.NET2002orVisualStudio.NET2003
ManyofthecodesamplesinthebookcanalsobeusedwithMicrosoft
VisualC#.NETorwiththecommand-linetoolsintheMicrosoft.NET
Framework1.0(or1.1)SoftwareDevelopmentKit(SDK).However,
becausethesetoolsdon'thavethesamecapabilitiesasVisualStudio
.NET,thetasksdescribedinthebookwillbedifferentfromyour
experience.


Support
Everyefforthasbeenmadetoensuretheaccuracyofthebookandthe
companioncontent.MicrosoftPressprovidescorrectionsforbooksand
companioncontentthroughtheWorldWideWebat
/>Ifyouhavecomments,questions,orideasregardingthebookorthe
companioncontent,pleasesendthemtoMicrosoftPressbye-mailto
orbypostalmailto
MicrosoftPress
Attn:ExtremeProgrammingAdventuresinC#Editor
OneMicrosoftWay
Redmond,WA98052-6399
Pleasenotethatproductsupportisnotofferedthroughtheabove
addresses.SupportforMicrosoftproductscanbefoundat
.

Acknowledgments
Itisimpossibletoproperlyacknowledgeeveryonewhoplayedan
importantroleinthecreationofthisbook.Hereisashortlist:
Myfamily,withoutwhomI’dnotbehereandnotbewhatIam:my
parents,RonaldE.andMargaretS.Jeffries;mybrothers,Dick,Tom,and
Pat;mywifeRicia;mysonsRonandMike.
Myforebears,betters,andcolleaguesintheXPandagilecommunity:
WardCunningham,KentBeck,MartinFowler,AlistairCockburn,Jim
Highsmith,AndyHuntandDaveThomas,BobMartin,andsomany
more.
ThemanypeopleinterestedinExtremeProgrammingandagilemethods
whohavehelpedmetofigureoutwhatIwastryingtosay,bywading
throughsomanyideasonmailinglistsallovertheInternet.


Mypal,pairprogrammer,andcolleague,ChetHendrickson,andmypair
programmingpartner,PaulFriedman.
MyeditorsLindaEngleman,withoutwhomthisbookwouldnothave
happened;DevonMusgrave,withoutwhomitwouldhaveappearedtobe
insomestrangenewversionofEnglish;mytechnicaleditorsLeeHolmes
andKyleCordes;reviewerDominiquePlante;andthemanyotherswho
haveofferedideas,help,andcriticismalongtheway.JimLeValleyat
MicrosoftPress,whosupportedtheprojectfromtheverybeginning.And
themanypeoplebehindthescenesatMicrosoft,includingCarlDiltz,who
pagedthebook,JulieKawabata,whocreateditsindex,andJoel
Panchot,whocreateditsart.ThanksalsofortheproofreadingofSandi
ResnickatMicrosoftandtheteamatNSightWorks:JoeArmstrong,Steve
Boudreault,CatherineCooker,KerinFoley,BethLew,KatieO'Connell,
DanShaw,AsaTomash,andMelissavonTschudi-Sutton.



SoundBites
Hereareafewmorewordsonthe“soundbite”lines,indicatedbysb,that
litterthebook,aswellasafewonbonussoundbitesnotfoundinthe
book.
Aretheobjectshelpingus?(Chapter31,page482)
Sometimesaswe’reprogrammingalong,thingsgoverysmoothly.It’sas
ifalltheobjectsandmethodsarereachingout,alwaysreadytohelpus.
Othertimes,itseemsthattheyarehiding,duckingoutoftheway,fighting
usforeveryinch.Ifwe’resensitivetothesefeelings,wecanbeginto
sensewhenthecodewe’reworkingwithisn’taswell-designedoraswellstructuredasitneedstobe.Doyouhavetotellsomeobjectaboutten
thingsbeforeitwilldoanythinguseful?It’snothelping—maybeyoucan
fixit,orfindabetterhelper.
Arethetestshelpingus?(Chapter31,page481)
Usuallywe’llfindthatourtestsleadusthroughnewareasandprotectus
aswechangethings.Butsometimestheyseemtoletusdown.Arebugs
croppingupinsomeareasofthecode?Evenifweareusing“Findabug,
writeatest,”wemightseecontinuingweaknessinsomeareaofthe
code.Codeweaknesscanslowusdownprofoundly.Itcanbeworthwhile
tothinkaboutandinstallanewapproachtotestingthatarea.
Automatedtestsrecordourintelligenceforlater!(Chapter5,page
65)
Arewehavingtroublecreatingsomenewchunkofcode,evenusinga
test-drivenapproach?Arethetestshardtowriteorhardtomakework?
Considerturningattentiontothetestsforawhile.Testbyusinga
differentapproach,attackingadifferentcorneroftheproblemorfroma
differentangle.
Ifyou’relikeme,sometimesyouwritealittlepatchofcodetolearnhow
someobjectworksandtogetasenseofhowtouseit.Myhabit,formed
overmanyyears,istowritealittlemainprogramthattriessomethingand



perhapsprintsafewvalues.Imakeitwork,learnfromit,andthenthrow
itaway.
I’mtryingtotrainmyselftowriteaTestFixtureinstead,whichhastwo
advantages.First,usingthetest-orientedpartofmybrainseemstohelp
melearnalittlemore.Second,thetestrecordstheuseoftheobject,and
theresults,inaneasytofindformforlater.Giveitatry—youmightlikeit!
Beginwithatest.(Chapter25,page323)
Asprogrammers,wetendtothinkintermsofalgorithmsandsolutions.
Weseeaproblemandvisualizeawaytoprogramit.Andthere’sgreat
joyinputtingsomesweetlittlealgorithmtogether.Forme,though,that
wayoftenleadstodebugging.Iwriteabunchofcode,finallygetaround
totestingit,anditdoesn’tquitework.
ThedisciplineItrytouseistosaytomyselfwheneverIsitdownto
program,“Beginwithatest.”SometimesIlistentomyselfandactuallydo
it.ItalwaysworksbetterwhenIdo.
Buildsimplescaffoldingandthenimproveit.(Chapter17,page216)
Becauseprogrammingissomuchfun,it’seasytogetcarriedaway,
buildingcomplexsoftwaretosupportsimpleneeds.Because
“infrastructuredoesn’tpleasethecustomer,featuresdo,”we’lloftenbe
moresuccessfulifwebuildjustenoughinfrastructuretothecurrent
situationanddon’telaborateitbeyondthecurrentneed.Whatwebuild
needsalwaystoberobust,well-tested,well-crafted.Butwecanleaveoff
thebellsandwhistles,untilthecustomercallsforringingandhooting.
SeealsoYAGNI—YouAren’tGonnaNeedIt.
Card,Conversation,Confirmation.(Chapter6,pages71-72)
XP-styleplanningisinsomewaysmyfavoritepartofExtreme
Programming,althoughwebarelytouchedonitinthisbook.The
techniquescanhelpateamfocusonwhat’simportantandwhatshould

beputoff,theycanhelpusfigureouthowlongthingswilltake,andthey
canhelpuskeeptrackofhowwe’redoing.Ifyoudecidetolearnmore


aboutXPplanning,youshouldkeepthreethingsinmind:
CardThenamesofstories,andperhapsafewwordsabout
them,arewrittenoncards.Thesecardsaretokensrepresenting
therequirement,andwecanusethemtolayoutaschedule,to
signifythatwehaveacceptedresponsibilitytoimplementa
feature,oraspartofadisplayofwhat’sdoneandwhat’sleftto
bedone.Butthecardisnotthefullrequirement,justatoken
containingtherequirement’sname.
ConversationThereisanexchangeofinformationbetweenthe
Customers,thepeoplewhounderstandtheneed,andthe
Programmers,thepeoplewritingtheprogram.Tobuildafeature,
theprogrammersneedadeepunderstandingofwhatneedsto
bedone.Thisknowledgecanbeprovidedbywritten
requirementsspecificationsaspartoftheConversation,butwe
callitConversationtoemphasizethatunderstandingcomes
fasterandbetterinapersonalconversationthaninpassing
documentsbackandforth.Sowritewhatyoumust,andexplain
asmuchasyoucan,facetoface.
ConfirmationNomatterhowmuchwewrite,andnomatterhow
muchwetalk,therewillbemisunderstandings.Ifwecode
accordingtoamisunderstanding,thecustomerwon’tbehappy.
Tighteningupourdocumentsandlengtheningourreviewcycles
reallywon’thelp—humanlanguageisinherentlyambiguous.
Therefore,expressthedetailsofstoryrequirements
unambiguously,inCustomerAcceptanceTests.Gettingthese
testsdefinedandagreedto,you’llnaildowntherequirements

quickly.Thetestswillhelptheprogrammersknowwhentheyare
doneandwillhelpthemavoiddefects.Finally,runningthetests
willgivethecustomeraconcreteunderstandingofhowthingsare
going.Card,conversation,confirmation—don’tdosoftware
withoutthem.
Dailybuildsareforwimps.(ExtremeProgramming,pagexxix)
Mostteamsnowrealizethatweeklyorlongerbuildcyclesareadisaster


—thebuildalwaysbreaks.Ioncevisitedateamthatwassevenweeks
behindontheir“weekly”builds!Dailybuildsareagreatimprovement,but
theyonlyscratchthesurfaceofwhatcanandshouldbedone.Many
teamsstrikedownwithharshconsequencesuponanyonewho“breaks
thebuild.”Theyarerighttowantthebuildnottobreak,butIsuggestthat
itisateamissue,notablameissue,whenthebuildbreaks.Stopthe
wholeassemblyline,figureoutwhatwentwrong,andfixtherootcause.
Buildingmanytimesperdayisparadoxicallyeasierthanbuildingonce.
Firstofall,thechangesthatcanbemadeinanhourortwodon’tdeviate
aswildlyasthosesavedupforawholedayormore,soanhourlybuildis
muchlesslikelytobreak.Second,ifbreakingthebuildisateamissue
andwebuildmanytimesperday,wewillgetverygoodatit.Thoseroot
causesofbreakswillbediscoveredandcorrectedquickly.
Designallthetime.(Chapter1,page8)
Designisn’tsomethingthatwedojustatthebeginningofaprojector
storyortask.Aswework,we’llencounterdesignissuesallthetime,
whetherwe’recodingandfindsomethingawkward,testingandfind
somethingdifficulttotest,orevenifwe’rejustdesigning.Ifwecanbe
sensitivetoemergingdesignissuesandrespondtothemimmediately,
thedesignwillstayclosertogoodallthetime.
Don’tfallinlovewithourownwork.

Sometimeswecodeupsomethingreallyniftyandwe’reprettyproudofit.
That’sgood—it’simportanttopracticeandtoexerciseourskills.
Sometimesweworkreallyhardonsomethingandfinallygetittowork.
That’sgoodtoo—sometimeswehavetogetthingsdoneevenifthey
aren’tentirelypretty.
Butboththesesituations,andothers,cansometimesblindustothefact
thatthere’sabetterwaytodowhateveritis.Whenwefeelourselves
resistingchange,defendingourcodelikeitwasourdearestchild,it’s
morelikelytimetoletgo.Don’tfightback.Pretendthatsomeoneelse
wrotethatpieceofjunk,andgetonboardwithseeingwhat’swrongwith
itandhowtomakeitbetter.Thendecidewhattodo.


Endtoendisfurtherthanyouthink.(Chapter13,page182)
Whenwetestourproduct,wealwaystrytotestit“fromendtoend.”We
wanttomakesurethatinputscomeincorrectly,getprocessedcorrectly,
andturnintooutputscorrectly.Paradoxically,italwaysseemsthatthe
worstproblemsoccurjustbeyondthecurrentedgesofourtesting.When
thishappens,there’snotmuchwecandobutpushtheendsoutabit
further.Iguesswejusthavetogetusedtoit...
ExpressingIntention.(Chapter4,page42)
Wealwayshavesomethinginmindasweprogram,atleastIhopewe
do.Whenwehavefinishedsomething,oftenourintentionschangedabit
alongtheway,aswelearnedwhatthecodereallywantedtodo.
Therefore,aswefinishupsomepieceofcode,let’slookbackatit,andat
whatweweretryingtodo,andseewhetherthecodeexpressesthat
intention.
Wehaveallhadthatjoyfulexperienceofreadingsomestretchofcode
andsuddenlyseeingwhatsomepartofitdoes:“Look,thisbitupdatesall
thependingrequests,thenthisbitselectsonerequest,thenthenextbit

processesthatrequest!”It’skindoffuntofigureoutthatstuff,butittakes
timeandenergy.Let’schangethecodetosaywhatitdoes:
UpdatePendingRequests();
RequesttoDo=SelectNextRequest();
ProcessRequest(todo);
...
Sometimesit’sevenagoodideatoprogramtheintentionsfirstandfillin
thedetailslater.Wecallboththesepractices“ExpressingIntention.”
Fakeitbeforeyoumakeit.Fakeittillyoumakeit.(Chapter11,page
146)
Intest-drivendevelopment,wedobestwhenwecycleveryquickly
betweenwritingatestandmakingitwork.Onewaytospeedupthis
cycleistosendamessagetotheobjectundertestand,ratherthanwrite
thecodetoreturnafullyrobustanswer,merelyreturnaconstant.Then


wewriteasecondtestthatrequiresustofillinthedetailsofthemethod.
Thispracticeseemsoddtomostpeoplewhentheyfirstencounterit,but
manyofusfinditausefulapproach,especiallyatthebeginningofanew
classormethod.Giveitatry!
Findabug,writeatest.(Chapter5,page58)
Wedon’twantbugsinourcode,right?Wefindbugswithtests,right?By
writingtests,wepreventotherpeoplefromembarrassingusbyfinding
bugs,right?Therefore,ifabugisfound,wehavemissedatleastone
test.Let’swriteit,thinkaboutit,andlearnfromittowritebettertestsin
thefuture.And,asausefulsideeffect,whenthenewtestsrun,thebugis
probablyfixed!
Infrastructuredoesn’tpleasethecustomer;featuresdo.(Chapter
30,page472)
Ofcourse,wecan’tdotheprogramwithoutinfrastructure.Let’s

recognize,though,thatbuildinginfrastructureisanecessaryevil,and
let’sdoitasfrugallyandincrementallyaswepossiblycan.Unused
infrastructureisawasteuntilitisused.Deletedfeaturesreducecustomer
happiness.Putthesetwofactstogetherandbuildinfrastructure
incrementally,asneeded,insupportoffeatures.
Isolatetheunknown.
Oftenwhenwe’reworkingonsomething,weknowhowtodomostofit
andthere’sjustthisonepartwedon’tknowhowtohandle.Isolatethat
part,viaoneoftwoways:
Wecanbeginbyfocusingonthatpart,writingtestsaboutit,
programmingit,andsolvingit.Now,sinceweunderstandthe
rest,everythingiseasy.
Orwecanpretendthatweknowthesolution,programasifit
exists,andgettherestoftheprogramlaidout.Nowwecanfocus
ontheunknown,andoftendoingwhatweknowhasmadethe
unknownmoreclear.


It’sChet’sfault.(Chapter11,page139)
“Whobrokethebuild”isacommonquestionbutthewrongquestion.We
allbrokethebuild,throughomissionandcommission.Whenaproblem
occurs,ask“why,”not“who.”Tohelpwiththis,wehaveChet.Intheearly
daysofExtremeProgramming,theteamwasonahunttofigureoutwho
toblameforsomething.ChetHendricksonstoppedthemeeting:“Stop!
It’smyfault!Here,look,I’mwriting’It’smyfault’onthiscardandsigning
it.Fromnowon,everythingismyfault.”So,whenyou’rewondering
whosefaultitis,nowyouknowtheanswer:it’sChet’sfault.Nowget
downtofiguringoutwhyithappenedandwhattodoaboutit.
Keepthetestsongreen.(Chapter17,page213)
AsIreflectbackonthisbook,Icanseethatwhenmytestsweregood

andallworkingexceptforonenewone,thingswentratherwellandIwas
relaxedandmoreproductive.Whenmytestswereweakornotrunning
well,Iwastenseandlessproductive.Ilikerelaxedandproductivebetter.
That’swhyItrytobeginwithatestandwhyItrytokeepallthetests
green.
Makeitwork;makeitright;makeitfast.(Chapter17,page215)
Thismightbetheoldestadviceincomputing,exceptfor“Mr.Babbage,
don’tgetyourtieinthegears!”Ican’tfindtheoriginalsource,butinany
caseit’sgoodadvice.Firstmakethecodegettherightanswers.Don’t
spendtimehoningoroptimizingcodethatdoesn’tworkyet.Whenit
works,honeittomakeitclean.Don’twastetimeoptimizingcodethatis
hardtounderstand.Then—andonlythen—ifaperformancetestshows
thatthiscodeistooslow,makeitfast.
Outerdesignshoulddriveinnerdesign,always.(Chapter30,page
473)
There’snotmuchmoreirritatingthanprogrammingwithobjectsthat
aren’thelpingus.(SeealsoAretheobjectshelpingus?)Testsareone
goodwaytofindouthoweasyorhardanobjectistouse.Ifit’shardto
test,it’sprobablyhardtouse.Plus,it’softenbesttoprogramtopdown,to
betterfindoutwhattheobjectsneedtobe.


Programmingwithoutthinking…whatgoodisthat?(Chapter30,
page473)
Sometimesitfeelslikewe’rejust“crankingoutcode”byrote,almost
withoutthinkingaboutit.Thiscanbeasignthatwhatwe’redoingneeds
tobeautomatedinsomeway,orperhapsweshouldask,“Aretheobjects
helpingus?”Ifyou’reprogrammingandnotthinkingaboutit,thinkabout
it.
Pushalittlewhensomethingseemstoohard.(Chapter17,page

216)
SometimesIknowwhatI“should”do,butitjustseemstoohard.When
thathappens,it’softenvaluabletopushabit.SometimesIpushmyself
tostartonthedifficult-seemingthing.OftenonceIgetstarted,Icankeep
going.OthertimesIpushontheideaofwhyit’shard.DaleEmeryrefers
to“ResistanceasaResource.”Whenwhatwe’redoingisresistingus,
therecanbevalueinpushingbackabit.Ofcourse,therecanalsobe
valueinturningasideandgoinganotherway.Ineversaidthatallthis
wouldbecomeobvious!
Reflectonhowthingsaregoing.(Chapter30,page469)
It’sgoodtopausefrequentlytoseehowwe’redoing—anothergood
reasontodrinklotsoffluids.Sitstillforamoment,clearyourmind,and
payattentiontoyourbody.Isittense,uncomfortableinsomeway?Is
yournecktight?Areyoufrowning?Isanythingnaggingatyou?Isthe
codetryingtotellyousomething?Areweontherightroad,goinginthe
rightdirection?
Removingduplicationisyourfriend.(Chapter11,page151)
It’sfascinatinghowvaluableitistoobserveandremoveduplicationinthe
code.Duplicatecoderepresentssomeideathatisbeingusedoverand
over.Toremoveit,wehavetoclarifythatideaandgiveitanameanda
placetobe.Thecodegetsbetterinsmall,smoothsteps.Duplicationcan
occurinspace,intime,orinconcept.Thinkaboutit,observeit,and
mindfullyremoveit.


Solvewhatyouknow;leavethepartsyoudon’tknowforlater.
(Chapter6,page78)
SeealsoIsolatetheunknown.
Someverysimplerefactoring…hasdonemostofthejobforus.
(Chapter22,page268)

Sometimeswegettoapointwherethesolutionwehavebeenworking
onturnsouttobewrong.Ourreactionisoftentostartoveronanew
solution,butthereisanalternativeandit’softenbetter.Partsofourbad
solutionmightwellbeprettygood;otherwise,wewouldn’thavebeen
goingthatway.Considerrefactoringthesolution,extractingthegoodpart
fromthebadorthebadfromthegood.Indoingso,there’sagood
chanceyou’llteaseaparttheknownfromtheunknown.Thenjustfixthe
partthatneedsitwithoutwastingthegoodbitsordoingthemover.
Startanewpathwithsomethingabysmallysimple.(Chapter4,page
45)
SeealsoFakeitbeforeyoumakeit.Fakeittillyoumakeit.andWhatis
thesimplestthingthatcouldpossiblywork?Dothesimplestthingthat
couldpossiblywork.
Thestory’snotdoneuntilthecustomertestsrun.(Chapter6,page
72)
UseCustomerAcceptanceTests—the“Confirmation”partofastory—as
ameansofcommunicating,butalsoasameansoffeedback.Clearly,we
can’tcallastorydoneuntilthetestsrun,butweshouldstrivealsotobe
donewhenthetestsallrun.Ifthetestsrunbutsomefunctionalitystill
needstobeadded,eitherthetestsareincompleteorwe’reworkingon
somethingthatthecustomerdoesn’twant.Ifthetestsrunbutthereisstill
alotofrefactoringorcleanuptodo,byallmeansdoit,buttryalsoto
needonlyalittlecodetocleanupbeforethecodeisreadytogo.
Refactoringworksbestinsmalldosesallthetime,notinbigbites.Use
themomentwhenthetestsrunasatimetoseewhetheryourrefactoring
iskeepingup.


×