Tải bản đầy đủ - 0 (trang)
Chapter 3. Do One Thing, and Do It Well

Chapter 3. Do One Thing, and Do It Well

Tải bản đầy đủ - 0trang

Youcanprotectyourselffromdisaster.Ontheriver,Inow

planforsafetyonesmallsectionatatime.Whilecoding,we

mustbuildtestcasesthatidentifyproblemsquicklyineach

logicalsection.

Youcanbetterreusetechniquesandcode.Ontheriver,I

learnnewmovesthatIcanuseelsewhere.Insteadof

franticallypaddlingthroughasection,Iuseadrawstroke

toavoidonerock,anaggressivebraceandsweeptopunch

ahydraulic,andsoon.Incode,Ibuildcollateralandlearn

techniquestosolvesmaller,moregeneralproblems.Each

designpatternthatyoulearnincontextisworthany20

thatyoureadabout.

Whetheryou'reakayakerrunningaClassVrapid,aphysicist

workingonaspacestation,oraprogrammerdealingona

massiveproblem,yourapproachshouldbethesame.



Understandtheproblem

Youmustunderstandaproblemtosolveitwell.Effective

programminggoesbeyondyourcodeeditoranddebugger.

Youneedtobeabletoaccuratelygatherrequirements,and

controlthescopeandexpectationsofyourcustomers.

Thereisnothingworsethanasolutionwithoutaproblem;it

justgeneratesmoreproblems.



Distilltheproblemtoitsessence

It'softensaidthatprogrammingismoreofanartthana

science.Nowhereisthisaxiommoreobviousthaninthe

abilitytocutthroughclutterandfindthecoreproblem.

You'vegottorecognizewhatbelongsinthecenterofyour



problemspaceandwhatyoucanpushouttootherclasses

aroundtheperimeter,oroutoftheprojectaltogether.Most

ofthetime,lessismore.



Layerthearchitecture

Ifyou'resolvingadifficultproblemandyoucanonlyfocus

ononethingatatime,youmustlayeryourarchitecture,

witheachlayerhandlingonetask.Thebroadest,most

successfuldesignpatternshelpyoubuildeffective,

decoupledlayers.Model-view-controllerletsyoudesignuser

interfaceswiththreelayeredcomponents.Faỗadesallow

youtobuildcleaninterfacesbetweenmajorlayersinyour

application.Ifyouliketostudydesignpatterns,pay

attentiontohowoftenthisthemearises.



Periodicallyrefineyourapproach

Lefttoitsowndevices,softwarelosesfocusovertime.

You'vegottomakeaconcentratedefforttorefactor,

decouplingyoursoftwareintoautonomouslayers.

Automatedtestswillhelpyourefactorwithconfidenceand

designdecoupledcodeinthefirstplace.Gettingfeedback

fromteammatesandclientsoftenhelpsmakesurethe

approachstillsolvestherightproblems.

Inthischapter,weexploreeachoftheseconceptsindetail.You

don'tneedtogothroughthemalltoseeadifferenceinyour

programmingyoucanbenefitfromeachtechniqueindividually.

Butcombiningthemmultipliestheirimpact.



3.1UnderstandingtheProblem

Communicationisahugepartofprogramming.Writingbetter

Javawon'tdoyouanygoodifyou'rebuildingthewrongthing:

youmustunderstandbeforeyoucancode.Asyouadvancein

yourprogrammingcareer,you'llfindthatmoreandmoreof

yourjobdemandseffectivecommunication.Itdoesn'treally

matterwhereyourrequirementscomefromyourteamlead,an

analyst,orthecustomer.Ineachcase,yourfirstjobisto

accuratelygathereachrequirementandfocusyourcustomeron

whatyoucanreasonablyachievewithyourresourcesathand.

Don'tplowyourcustomerunderwithenormousrequirements

andarcanedesigndocuments.Ifthecustomerscan't

understandyourdocuments,theycan'tfocusontherealissues.

Likeyourcode,keepyourrequirementssimpleandclear.

Ifyoudon'tlikecommunication,I'vegotnewsforyou:things

aregoingtogetworsebeforetheygetbetter.Inaglobal

economy,you'vegottobeefficient.Increasingly,thatmeans

developersmusthandlemoreandmoreofthesoftware

developmentprocess.Outofcollege,Iworkedforthelargest

softwarecompanyintheworld.Wehadmoretestersthan

codersonaproject(often,byafactorof3to1),andteamsof

10plannerssupporting40developers.Theoveralleffortwas

200developersstrong.Now,thatprojectmightuse10

developersandhalftheoriginaltimeframetodevelopthesame

pieceofsoftware.Sincethedevelopmentofbetterautomation

andunittesting,eachmoderndevelopermustshouldermoreof

thetestingload.Codersalsodomoredesignworkandplanning

thaneverbefore.However,experienceshowsthatmanyof

thosedevelopersarenotequippedtohandlemanyofthe

increasedplanningandanalysisrolesthattheyface.



3.1.1GatheringRequirements



Thisbookwouldnotdoitsreadersjusticeifwedidn'ttalkabout

dealingwithchangefromaprocessperspective.Ifyou'reoneof

thoseshopsthattriestodomorewithless,youneedtodotwo

thingsintheplanningprocess:first,weedoutsoftware

requirementsthatdon'tcontributemuchtothefinalproject,

andsecond,weedoutunnecessaryworkthatsupplements

traditionaldevelopmentbutdoesnotcontributemuchtothe

overallcontentorqualityofyourcode.

Manyprogrammersbelievethattheyneedtobuildobjectorienteddesigndocumentslikeclassdiagramsorobject

interactiondiagramsinordertosupportdevelopment.The

dangerwiththisapproachisthatyoucanspendtoomuchtime

maintainingyourdesigndocumentation,andnotenoughtime

buildingworkingcode.Thebestdesignresourcesarea

lightweightrequirementslist,workingcode,andanon-site

customer.Arequirementsdocumentoftenconsistsoflittlemore

thansinglelineitems,eachtakinglessthanhalfadayto

severaldaystocomplete.Often,youdon'tneedformalproject

managementsoftware.I'vemanagedrequirementswith

expensiveprojectmanagementtools,wordprocessor

documents,andspreadsheets.Lowtechusuallyworksbetter

thanhightech.



3.1.2ControllingScopeCreep

Onceyou'vegotrequirementstogether,you'llwanttokeepa

manageablescope.Ioftenspendagooddealofmytime

improvingcommunicationandunderstandingatclientsites.By

far,thebiggestproblemsIencountercomefromcontrollingthe

scopeandexpectationsoftheproject.Often,thepowercomes

fromapocketbook,soit'stemptingforthoseinchargetotryto

addwhateverfeaturestheywant,whenevertheywantthem.

There'sanecessarytensionbetweenproductivityandchange.

Manyteamssucceedbecausetheyadapttorapidlychanging

requirements,butjustasmanyprojectsfalterbecauseteams



failtoadequatelycontrolscope.Thisisthecentralproblemin

softwaredevelopment.Theonlywaytoeffectivelydevelop

softwareistosucceedatsolvingthisproblem.



3.1.2.1Managinggoodchange

Iterativedevelopmentiseffectivepartiallybecauseitallowsyou

toadapt.Butregardlessoftheprocessthatyouuse,your

customersmustunderstandtheoverallcostofchange.

Wheneversomeonerequestssignificantchanges,youcan't

threatentobeatthemwithaplasticwhiffleballbat.You'vegot

tobereceptivebutfirm.Yourfirstresponseshouldbe

somethinglike,"We'lltrytoworkitin.Letmetellyouwhatit

willcost."Thistypeofanswerimmediatelygivesyourcustomer

positivefeedback,andalsoletsthemknowthatchangeaffects

theoverallcostoftheproject.Itdoesn'tmatterwhothe

customeris.Whetheryourprojectisinternalorexternal,some

factsnevervary:developmenttakesmoney,time,and

manpower.Youcanonlydosomuchwithagivenpoolof

resources.

Figure3-1illustratesthethreewaysyoucanreacttoexpanded

requirements:

1. Reducetheremainingscopebyremovingan

unimplementeditemofthesamecostfromthis

release.

Increasethetimeallotted:requestmoretime,andaskfor

moremoney.

Increaseyourmanpower:askformoremoney,andincrease

yourteamsize.



Figure3-1.Reactingtoexpandedrequirements



Youcanalsocombinetwoormoreoftheseoptions.Thefirst

methodisbyfarthebest.

Noticethatincreasinghoursisnotaviableoption.Heavy

overtimemeansthattheprojectmanagersarenotdoingtheir

job.(Increasingly,thedeveloperistheprojectmanager!)Heavy

overtimeusuallyleadstodefections,mistakes,andsloppiness

thatcostmoreinthelongrun.Norshouldyouincreaseyour

manpowerinotherways.Unlessyou'regrosslyunderstaffed,

increasingthesizeofanoptimalteamisgoingtosacrifice

efficiency,andmayevendelaytheprojectfurther.Scheduling

conflictsalsocauseproblems.Ifyoufrequentlyslipyour

schedules,you'redelayingthevaluetoyourcustomers,and

that'srarelyagoodidea.

Byfar,thepreferredwaytopayforachangeinareleaseisto

pushotherfunctionsoutoftherelease.Ifyougetintothehabit

ofnegotiatingahealthygive-and-takewithyourcustomers,

they'llgetbetteratunderstandingofwhat'smostimportantto

them,andyou'llgetaccustomedtodeliveringonyour

commitments.



3.1.2.2Curtailingdisruptivechange



Theabilitytoreacttoyourcustomersisimportant,butnotall

changeisgood.Disruptivechangekeepsyourcodeoutofthe

handsofyourcustomers,andcodethat'sinthelabdoesn'tdo

yourcustomersanygood.Disruptivechangetakesseveral

forms:

Uncheckedscopecreepcanquicklyderailanyproject.You

mustconsciouslymitigateeachchangeinscope,anddoso

withminimaldisruptiontoyourteamandschedule.That

usuallymeanspullingfeaturesoutforeachonethatyou

add.

Changesthatareoutsidethecentralpurposeofaproject

reducefocus.Thiskindofdisruptivechangeoftendeals

morewithinfrastructureandmiddlewarethanwithend

applications.Forexample,Ihaveseencustomersbuild

messagingintotheirpersistenceframeworks,orbusiness

logicintotheiruserinterfaces.Thesetypesofshort-term

compromisesusuallybackfire.

Changesoutsideofthenormalreleaseschedulesdisrupta

team,andchangesthathappenverylateinaniteration(for

example,afteracodefreeze)areespeciallydisruptive.In

general,youimproveyourabilitytochangebyshortening

iterationsratherthanforcingunnaturalchangeintoan

ongoingiteration.Figure3-2showsthecostofchangeat

eachstepinthedevelopmentcycle.Thesawtoothpatternis

characteristicofthecostofchangeinaniterative

developmentprocess.It'sbettertohavethecustomerwait

forthenextiteration.



Figure3-2.Attheendofeachcycle,especially

afteracodefreeze,changegetsmoreexpensive



Ingeneral,certaintypesofchangescausemorechaosthan

others:latechanges,largechanges,andshiftsinfocus.The

reality,though,isthatyou'regoingtohavechange,andunless

you'rebothdisciplinedandlucky,you'regoingtohavetodeal

withsomelatechange.Therestofthischapter,andthisbook,

dealswithadaptingtochange.



3.2DistillingtheProblem

Virtuososinanyprofessionhaveacommongift:theycandistill

aproblemtoitsbasiccomponents.Inphysics,Einstein

identifiedandcapturedmanycomplexrelationshipsinasimple

equation,e=mc2.Beethovencapturedandrepeatedamotif

consistingoffournotesinhisfifthsymphonythat'senduredfor

centuries.Programmingdemandsthesamefocus.You'vegotto

takeasetofrequirements,identifytheessentialelements,strip

awayeverythingthatdoesn'tbelong,andfinallybreakdown

andsolvetheproblem.

Toimproveyourprogramming,youdon'thavetoliveinacave,

readingaboutadesignpatternthatcoverseverypossibility.You

don'tneedtoknowthelatest,hottestframework.You'vejust

gottofocusontherightproblem,distillittothebasics,and

hammeroutthesimplestsolutionthatwillwork.Inthissection,

I'mgoingtotakeasetofrequirements,distillthem,andturn

themintocode.



3.2.1CollectingRequirements

Let'stakeasimpleexample.Saythatyou'rebuildinganATM.

Yourjobistobuildthesupportforanaccount.Inkeepingwith

Agileprogrammingpractices,you'vedecidedtokeepasimple

setofrequirementsinatable.You'llrecordtherequirement

number,abriefdescription,asize(timeline),andchoosea

programmer.Yourteamissmallandyourcyclesareshort,so

that'sallthatyouthinkyou'llneed.Table3-1showsthebasic

requirements.

Table3-1.Requirementsforaccountproject

Number



Description



Size(hours) Assigned



1



Keepabalanceandaccountnumber











2



Reportanegativebalance











3



Haveasix-digitaccountnumber











4



Don'tletuserschangetheaccountnumber











5



Rememberthebalancewhentheusercomesback











6



Letusersmakedeposits











7



Letusersmakewithdrawals











8



Displaythebalance











9



Displaydebit/creditbuttons











10



Printanewbalancewhentheuserisdone











11



Maketheaccountsecure











12



Displaythebank'slogo











13



Uselightercolors











14



Lettheusersprintouttheirbalance











15



Maketheusertypeafourdigitpassword











16



Maketheuserinsertacard











17



Itshouldbetransactional(itallworks,oritallfails)











Theserequirementsaretypicalofthetypesofthingsyou'llget



fromyourcustomers.Theyarefarfromcomplete,butthat,too,

isnormal.Thejoboftherequirementsdocumentisto

accumulaterequirementsasyouunderstandmoreaboutyour

application.Atthemoment,you'retheoneassignedtothis

task.You'llsizetaskslater.Atthispoint,youshouldfocuson

theproblemathand.Yourjobistobuildsupportforan

account.



3.2.2WhittlingAwaytheNoise

Yourfirstjobistowhittleawaysomeofthenoise.Takeanyof

theissuesthatmayfitneatlyelsewhereandpushthemoutto

theperimeter.Immediately,yourecognizethatyoushould

separatetheuserinterfacefromthebaseaccount.Youalsosee

thatkeepingabalancemeansthattheaccountwillneedtobe

persistent.You'lluseyourrelationaldatabase.Securityprobably

doesn'tbelongintheaccountitself;itwouldprobablybebetter

lefttoanotherlayerofthearchitecture,likeperhapsafaỗade,

butsecurityisalsoaspecialcase.Toomanydeveloperstreat

securityasanafterthought,somethingtheycansprinkleontop

ofanapplicationtomakeit"safe."Nosuchpixiedustexists,

though;securitylayersshouldbetreatedwiththesamerespect

youshowtoeverythingelseinyourcode.

Essentially,youneedtobuildapersistentaccount.Ratherthan

tryingtobuildadesigndocument,you'llstarttocode.It'sa

smallenoughproblemtogetyourheadaround,andyoucan

alwaysrefactor.Infact,you'llprobablyrefactorseveraltimesas

youthinkofwaystosimplifyandimproveyourdesign.Thenew

setofrequirementsisshowninTable3-2.

Table3-2.Updated,whittled-downrequirements

Number

1



Description

Keepabalanceandaccountnumber



Size(hours) Assigned

2



BT



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Do One Thing, and Do It Well

Tải bản đầy đủ ngay(0 tr)

×