0% found this document useful (0 votes)
84 views7 pages

Dont Repeat Yourself

The DRY principle states that every piece of knowledge in a system should have a single unambiguous authoritative representation to avoid duplication. Duplication can lead to inconsistencies and maintenance issues. While some duplication like generated code from IDL definitions is acceptable if the authoritative source is clear, the goal is to eliminate unnecessary duplication of knowledge. Temporary duplication may be needed to understand how best to remove it permanently through refactoring once more examples are known.

Uploaded by

ms6675
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views7 pages

Dont Repeat Yourself

The DRY principle states that every piece of knowledge in a system should have a single unambiguous authoritative representation to avoid duplication. Duplication can lead to inconsistencies and maintenance issues. While some duplication like generated code from IDL definitions is acceptable if the authoritative source is clear, the goal is to eliminate unnecessary duplication of knowledge. Temporary duplication may be needed to understand how best to remove it permanently through refactoring once more examples are known.

Uploaded by

ms6675
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

26/03/14

Dont Repeat Yourself

DontRepeatYourself
Context: Duplication(inadvertentorpurposefulduplication)canleadtomaintenancenightmares,poorfactoring,andlogicalcontradictions. Duplication,andthestrongpossibilityofeventualcontradiction,canariseanywhere:inarchitecture,requirements,code,ordocumentation.The effectscanrangefrommisimplementedcodeanddeveloperconfusiontocompletesystemfailure. OnecouldarguethatmostofthedifficultyinY2Kremediationisduetothelackofasingledateabstractionwithinanygivensystemthe knowledgeofdatesanddatehandlingiswidelyspread. TheProblem: Butwhatexactlycountsasduplication?CloneAndModifyProgrammingisgenerallycitedasthechiefculprit(seeOnceAndOnlyOnce,etc.),but thereismoretoitthanthat.Whetherincode,architecture,requirementsdocuments,oruserdocumentation,duplicationofknowledgenotjusttext istherealculprit. Therefore: TheDRY(Don'tRepeatYourself)Principlestates: Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem. It'sokaytohavemechanical,textualduplication(theequivalentofcachingvalues:arepeatable,automaticderivationofonesourcefilefromsome metaleveldescription),aslongastheauthoritativesourceiswellknown. Forexample,inamixedlanguageCORBAenvironmentyoumaychoosetotreattheIDLdefinitionsasauthoritative.Thesedefinitionswillbe usedtoautomaticallygeneratesourcecodefileswhichduplicatetheknowledgeintheIDL.Butthat'sokay:theIDLformoftheknowledgemeets therequirementsofourdefinition. Wheredifferentlevelsofabstractionareinvolved,aconsistentconflictresolutionschememustbeused.Thiscouldbeassimpleasidentifyingone levelasauthoritativeinallcases,oralwaysdeferringtothehighlevel,orwhatever,aslongasitisconsistentlyapplied. Forexample,inC++theinterfaceandimplementationforaclassaretypicallyspecifiedinseparatefiles,duplicatingknowledge.Youmayconsider theheaderfiletobeauthoritativeforthecontractoftheclassasviewedbyitsclients,andthesourcecodetobeauthoritativeregardingissuesof implementationwhicharehiddenbytheimplementation. Notes:ThisprincipleissimilartoOnceAndOnlyOnce,butwithadifferentobjective.WithOnceAndOnlyOnce,youareencouragedtorefactorto eliminateduplicatedcodeandfunctionality.WithDRY,youtrytoidentifythesingle,definitivesourceofeverypieceofknowledgeusedinyour system,andthenusethatsourcetogenerateapplicableinstancesofthatknowledge(code,documentation,tests,etc). Theprinciplealsoassumesthatyourprojectshaveahighdegreeofautomation,allowingthegenerationofthederivativeknowledgeartifacts wheneverrequired. AndrewHunt ThefollowingconversationsgetmuchsimplerwhenwerecognizethemostimportantthingtoDRYupis... declarationsofbehavior KeepingthestructureofaprogramDRYisharder,andlowervalue.It'sthebusinessrules,theifstatements,themathformulas,andthemetadata thatshouldappearinonlyoneplace.TheWETstuffHTMLpages,redundanttestdata,commasand{}delimitersarealleasytoignore,so DRYingthemislessimportant. PhlIp TheoppositeisWET: We Edit Terribly,Tumultuously,Tempestuously,Tenaciously,Toomuch,Timidly,Tortuously,Terrifiedly... IthinkWETalsostandsfor"WeEnjoyTyping" DuncanBayne

c2.com/cgi/wiki?DontRepeatYourself

1/7

26/03/14

Dont Repeat Yourself

But: Itmaytaketimeandefforttoselectand/orcreateadefinitivesourceseeYouArentGonnaNeedIt.DickBotting Hmm."Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem."Isthisnotareasonable definitionforaSingleton? No.DRYreferstoyoursourcecode,notyourrunningprogram.ThirdNormalFormistheanalogousprinciplefordata. Ugh.Ithinkyou'rebothbarkingupthewrongtreesthere.Itdoesn'trefertosourcecode,nortotherunningprogram.Itreferstoasystem.Needn't havecomputersinvolvedatall. InTheArtOfUnixProgramming,EricRaymondcallsthistheSinglePointOfTruthrule(SPOT). Iagreewiththis,"inprinciple".However,takenliterally,thisprincipleisimpossibletoachieve.Forexample,afunctionsignatureisduplicatedat thefunctioncallsiteandthefunctiondefinitionsite.Evenifyoudon'tdeclaretypes,thenumberofargumentsisafactthatisduplicated.Ipreferto thinkofgettingridofduplication(i.e.OnceAndOnlyOnce)insteadofneverhavingitinthefirstplace,becauseyoukeepdiscoveringthat somethingthatyoudidn'tthinkwasaduplicate,reallyis.Also,sometimesitismoretroublethanitisworthtoeliminatesomeduplication. Moreover,itisoftenbettertowaittilyouhaveseveralexamplesoftheduplicationsoyoucanbetterseehowtoeliminateit.RalphJohnson Ralph,that'sareallygoodwayoflookingatthings.Mybiggestprogrammingheadacheshavealwayscomefromabstractlystrugglingwith"how canIwriteagoodgeneralsolutiontothisproblem",eventhoughIonlyknowofoneplacewhereit'sdefinitelygoingtobeused."I'dbetterthink ofageneralsolutionnow,"Ithink,"orI'llhavetocopyandpasteandchangecode!"Butit'sabsurdtotrytocomeupwithageneralsolution withoutknowingmoreaboutthedifferentvarietiesoftheproblemthatexist(orwillexist)inthesystem. It'sabattleoftworeallystrongurgesOnceAndOnlyOncevsavoidingPrematureGeneralization.DoIduplicatefornowandtrytolivewiththe duplicationforawhile,orviolateYagNiandcomeupwithsomehalfcockedgeneralizedsolution?It'satoughone,becausealmostall programmershateduplicationit'sasortofprimordialprogrammingurge. However,eventhoughCopyAndPasteProgrammingcanbeexpensivetocleanup,soisabotched"generalsolution"andcopyandpasteisfar cheaperupfront.SoIalsoaminfavouroftemporaryduplication,toberefactoredwhenyouhaveaclearerviewofthesituation. MatthewBennett Alas,justexactlyhowIthoughtaboutit.Nowthetemporaryduplicationisahellishpermanentduplication.Ihavenotimetoremoveit,andthe moreIhavetoupdatetheeviltwinsofcode,thelesstimetoeverdosomethingaboutitiget.L.A.Nilsson (Formoreintheveinof"letaduplicationliveforawhile,inordertoseehowtobesteliminateit",seeCodeHarvesting.) IthinkthereisalsoacollisionwithDoTheSimplestThingThatCouldPossiblyWorkwhereIbelievethatlattershouldwinmostofthetime(aside fromthesituationswhererefactoringistoocomplicated,databaseschemas?) TheDRYprincipleisreallyaphilosophicalissue(althoughitdoesrearitsheadretroactivelyduringcoding).Theideaistotrytoplanaheadto preventduplication,ratherthattowastetimeremovingstuffyou'vealreadydone.Functionsignaturesareaformofduplication,albeitafairlyminor one,asthecompilershouldbeabletospottimeswhereonesidegetsoutofstep.It'sthemoreinsidiousduplicationwehopetostopwithDRY. Dave
' ' W h yi st h i sd u p l i c a t i o n ?N e i t h e rt h ep r o t o y p ea l o n en o rt h ef u n c t i o nd e f i n i t i o nc a r r i e s t h ef u l lm e s s a g e .W i t h o u tt h ep r o t o y p ee r r o r sw i l lc r e e pi n ,a n dw i t ho u tt h ef u n c t i o nd e f i n i t i o ne r r o r s c r e e pi n .T h i si sn o td u p l i c a t i o ni ti sv i r t u o u sr e d u n c a n c yw h i c hi n c e a s e st h et o t a le r r o rt r a p i n gp o w e r s y n e r g i s t i c l y .D i dIm i s st h ep o i n ts o m e w h e r e? ' '

Ilikethisprinciple.Perhapsrelatedtotheideaofbeingabletotraceanypieceofcodingbacktothereasonsforitsexistenceandform.Formea keypointistheselectionofoneitemasadefinitivesourceforcertainpurposes. Forexample,asintheabovedescription,I'dnormallytakeafunctionprototype/header/declarationasguidingthefunctioncalls.ThisiswhyIlike headerfilestocontaincommentsdescribingthecontract(makesurethefirstargumentpointsatrealstorageandthiscallwilldo.....foryou).The functionbodiesaredefinitivefortheimplementationdecisionsbutmightbederivedfrommoredefinitivegenericalgorithmsperhaps? DickBotting IfcodedoesnotconformtotheDRYprinciplecanwesaythatitiswet? Icertainlylikethisprinciple.Theapplicationsinembeddedsystemsshouldbeobvioustothecasualobserver.Canthepumpdispensemedication ornot?Onlyoneentityknowstheabsoluteanswertothispuzzler.Everycomponentthatneedstoknowwhatthemachine'scurrentstatusisgoes toawellknownmethod(aresource)tofindout.Whatunitsarewedealingwith,mlormg/cc?Eachcomponentmayneedalocalcopyofthis settingtofigureouthowtoconvert,buttheyallgotoacentralrepositorytoacquirethatknowledge.Mostexcellent,wouldn'tyousay? Let'stryasimpleXPcodingexample:

c2.com/cgi/wiki?DontRepeatYourself

2/7

26/03/14

Dont Repeat Yourself

areallthesesqrtexamplesreallymakingthepoint?Shouldwedeletethemormovethem?AnonymousCoward Agreedthesquarerootexamplekindawentoffonatangent,thediscussionitselfwasn'ttoobadbutitdoesn'tbelonghereAndrewRicketts{be boldaboutyouropinions} P1:OK,weneedasquarerootfunction.Letscodethefirsttestcase


t e s t 1 :a s s e r t _ e q u a l ( s q r t ( 4 ) ,2 ) ;

P2:andthecode:
s u bs q r t ( x ){r e t u r n2 ;}

P1:Hmm.OK,perhapsweneedanothertesttogetabetterimplementation
t e s t 2 :a s s e r t _ e q u a l ( s q r t ( 9 ) ,3 ) ;

P2:OK
s u bs q r t( x ){i f( x = = 4 ){r e t u r n2}e l s e i f( x = = 9 ){r e t u r n3}}

P1:Youcan'tdothat,you'rejustrepeatingtheinformationinthetest:itviolatestheDRYprinciple P2:Thatdoesn'tmatter.CodemustonlyobeyOAOO.DRYisjustphilosophicalclaptrap.Thetestsdon'tprovideenoughinformationto generalize,sothesimplestthingistoduplicatetheinformation. P1:No,itdoesmatter.Atestanditscodemustusedifferentalgorithmswhenexpressingthesameinformation.Iftheyarethesamethenthetest addsnovalue. Whoiscorrect?Whatimplementationwouldenablethetests+codetoconformtoDRY? ''Here'smyresolutionforthisparticularexample: Startwithagoodstatementabouttheprocesstodesignandtest. Documentedrequirement: 1. 2. 3. 4. 5. 6. 7. producethesquarerootof(x). Wheresqrt(x)*sqrt(x)=x. Errororimaginarynumbersmustbereturnedforx<0. x=0shouldreturn0. Insertedrequirement:xisintheRealNumberDomain. Insertedperformancerequirement:FunctionOverflowmustbeconsideredandreportedasanerror. Insertedperformancerequirement:AsFastAsPossible/DoNotBottleNeck.

Thenwriteyourtest:
f o r ( y = 1t o1 0 0 ){ x=r a n d o m _ i n _ r a n g e ( 1 ,s o m e _ m a x )-w h yn o tr e p l a c e1b ys o m e _ m i n-p o s s i b l yl a r g ea n dv e ? a s s e r t _ e q u a l ( x , s q r t (( x * x )) )

youmightalsowanttoconsiderassert_equal(x,sqrt(x)*sqrt(x))whichisadifferentproposition.DavidMartland
} a s s e r t _ e r r o r _ o r _ i m a g i n a r y ( s q r t ( 1 ) ) a s s e r t _ z e r o ( s q r t ( 0 ) )

noticethattherequirementdoesnotspecifyanupperdomain.Somodifiedthetestforrandomvalues>0.ThiswayMr.GuruCoderdoesn't getlazyandimplementanycomplexifstatements.Ifstatementnothing.Aguardclauseandatablelookup.MrGuruCoder.Ihappento knowfromexperiencethatsuchatabletendstogetexpensivewith32bitandlargerintegers(severaloptimizationsandIcouldn'tgeta PrimeNumbertablebelowaquartergigbeforegivingupbuthey,whataweekendofcoding). finallycodeandtestthesqrtfunction. WyattMatthews [Notedinpassing:Thistestdoesn'tseemtodomuchtowardverifyingthatthecodeworkswhentheargumenttosqrtisnotaninteger.Indeed,ifx isafloatingpointnumberthatisnotaninteger,thesquarerootofxcanneverberepresentedexactlyasafloatingpointnumber(Counterexample: sqrt(0.25)=0.5isperfectlyrepresentableinbinaryfloatingpointRV)(becausethesquarerootofanonintegerisalwaysirrationaldefinitely wrong:sqrt(0.01)==0.1,where0.01isnonintegerand0.1isrationalMrMathematician).Sotestingasquarerootprogramoutsidetheinteger domainisamuchharderproblem.AndrewKoenig]

c2.com/cgi/wiki?DontRepeatYourself

3/7

26/03/14

Dont Repeat Yourself

[Secondnoteinpassing:ImisspokewhenIsaidthatthesquarerootofanonintegerisalwaysirrational.WhatImeanttosayisthatthesquareroot ofanintegeriseitheranintegerorirrational.Now,anyfloatingpointvaluexcanbemultipliedbyanevenpowerof2toyieldaninteger.Callthe smallestsuchnumberN.Thensqrt(x*N)==sqrt(x)*sqrt(N),andbecauseNisanevenpowerof2,sqrt(N)isapowerof2.Becausex*Nisan integer,sqrt(x*N)iseitheranintegerorirrational.Ifsqrt(x*N)isaninteger,thensqrt(x)isanexactfloatingpointnumber,anditcanberepresented withhalfthesignificantbitsofx.Ifsqrt(x*N)isirrational,thensqrt(x)mustalsobeirrational,soitcannothaveanexactfloatingpoint representation. SowhatI'mtryingtosayisthatifyoutakethesquarerootofafloatingpointnumber,theneithertheresultisexact,andhaslotsofloworder zeroes,oritisanecessarilyinexactapproximationtoanirrational.AndrewKoenig] [Theassertionthatsqrt(x)canberepresentedwithhalfthesignificantbitsofxisnotalwayspreciselycorrect.] Thankstothecommentinsertedandtheblockbelow,Iwillnote,thatIdidn'twritethecodeforthesqrtfunctionasimpletablemaystillsufficeto bypassmydomainlesstestasitmaybeproventhatsqrt(x)=sqrt(y)*sqrt(z).Anyoneuponaproofthatthismight(ormightnot)work?Also, insteadofdoingastupidintegralsearch(asshownbelowitisonlystupidbecauseitdoesnotcheckfory*y>xandbreak)abinarysearchofthe RealNumbersDomainwillatleastaffordsomeadditionalspeed. WyattMatthews Ifxisaninteger...
i n ts q r t ( i n tx ){ i n ty=1 ; w h i l e( y * y! =x )+ + y ; r e t u r ny ; }

I'dliketoseeaproofthatthiswillhaltwhenxisanoddnumberotherthan1. Here'syourproof:Ifx=9,then:y=1,y*y=1y=2,y*y=4y=3,y*y=9.returnsy=3 OKbutitdoesn'thaltifxisoddandalsonotasquare.DavidMartland Moreappropriately,youshouldhaveaskedforaproofthatthefunctionwillpasstherandomtestifx=random_in_range(1,some_max)can specifynonintegralvaluesorvalues<=0withrespecttotherequirement.Asitstands,thisfunctionisnotcodedtosurvivealargeportionofthe IntegralDomain,muchlesstheRealNumbersDomain.Thisfunctionshouldberenamedtosomethingsuchas"IsXaPerfectSquare?"andmodified alittle. Attheleast,thestatedrequirementwants: error_codesqrt(intx,doubleresult){


e r r o r _ c o d er e s ; d o u b l et e s t ; i f ( x < 0 )r e s=e r r o r _ o r _ i m a g i n a r y ; e l s e { r e s=n o _ e r r o r ; i f ( x = 0 ) r e s u l t=d o u b l e ( 0 ) ; e l s e { / / S o m ec o d et os e a r c ht h er e a ln u m b e rs p a c e . / / Ab i n a r ys e a r c ht oac e r t a i nd e p t hf o re x a m p l e . } } r e t u r nr e s ;

} WyattMatthews IfyouprogramitinCstyle,atleastmakeitworkinC(passvariablesbyvalue,etc) TheSingleAuthorityaffordedbytheDRYprincipleandtheduplicationofthesourceasabasisfortheprogramenvironmentaddsinertiatothe system(seeRedundancyIsInertia)forthesakeofitsstability.Here'salittlelistthatIbelieveshowshowRedundancyIsInertia,theDRYprinciple, OnceAndOnlyOnce,andtestingshouldworktogether: thesingleauthorityistheinterface'ssignatureanddocumentedrequirements/goals.(RequirementsAndGoalsareanotherissue) theauthorityneedstobereadablebyanypotentialdirectuser.(ie:atextualorgraphicalrepresentationforthesoftwarewriterandabinary representationforthesoftware) theinterface'sbody(theprocess)mayduplicatethesignatureifandonlyiftheimplementationenvironmentrequiresit.

c2.com/cgi/wiki?DontRepeatYourself

4/7

26/03/14

Dont Repeat Yourself

TheprocessisafactItmustabidebyOnceAndOnlyOnceandtesttrueagainsttheauthority. R&Gmarkersmaybeplacedinthetextualcopyoftheprocessmuchaseditnotesaresometimesplacedthere. theuserduplicatesonlythepartofthesignaturerequiredtoestablishcommunications.(thecompilationprocessisallowedtoduplicatethe interface'sprocess.) theuseroftheinterfaceshouldonlyneedtesttheinterfaceagainsttheR&Gonceperlifecycle.(seeCategoryTesting) WyattMatthews Thereisapatterntotheexceptionstotheprinciple.Itisoktohavemorethanonerepresentationofapieceofknowledgeprovidedaneffective mechanismforensuringconsistencybetweenthemisengaged. DefinitionsanddeclarationsofCfunctions:theseareusuallyinsyncbecausethecompilerflagsinconsistencies,forcingtheprogrammerto takeaction. Unittests:inconsistencymeansthetestswillfail,againforcingsomeonetotakeaction. Autogeneratedstuff:periodicregenerationensuresconsistency. Oftentheeffectivemechanismisautomatedbutitdoesn'tneedtobe.Anexampleisenduserdocumentation:anautomatedmechanismfor verifyingsoftware/documentationconsistencyishardtocomeby(AiComplete?),soyouneedahumantoreviewthis.Amechanismtoensure consistencycouldinthiscasebeaninstructiononwhattodobeforeeachsoftwarerelease. AndersMunch DRYdoesn'tjustcombatinconsistency,though.Yes,apassedtestshowsthatcodeandtestareconsistent,buttheymaystillbothbewrong.Ifthe testandthecodehavethesameunderlyingstructure/knowledge,it'smorelikelythatadoublefailwillmakeapass.However,inmanyfunctions, it'seasytoeliminatethedoubleerrorsbecausetheirinverseisradicallydifferent.Forexample,considererrorcorrectingcodes:encodingisjusta hashwhiledecodingisacomplexoperation.Implementingtheencoderasatestreliablyfindserrorsinthedecoder. DRYsaysthatoneshouldstrivetouseadifferentimplementationintestandcodetoavoidthesameerrorinbothcausingafalsepositive.This actuallybringsupanotherpointwhatdoyoudowhentheonlywayofimplementingsomethingisidenticaltothewayyoutestit?Imustadmit I'mneverquitehappywhenIhavetodothat.Luckily,itusuallyonlyoccurswhentheoperationissosimplethatitbarelyneedstestingatall. JamesKeogh Seehttp://blogs.computerworld.com/but_it_seemed_like_such_a_good_idea_at_the_timeforanamusingdemonstrationoftheevilsofduplicate code. AristotlePagaltzis Postingalinkisitselfanamusingdemonstrationoftheevilsofduplicatecode(thislinkisavalidexample).MJones I'mstruckbythefactthatthisistheprinciplethatpushespeopletonormalizerelationaldatabases.It'snotwithoutitsdownsideconsideringthe reasonswhypeoplechoosestarschemas.ThereneedstobesomediscussionofwhenitisOKtoabandonthisrule.meta@pobox.com Actually,normalizeddatabasesrelyondataduplicationandoneusuallyhastowriteasetofconstraintstoensurethatkeyslinkingtablesare consistent.
H U H?T h ef a c tt h a tt h es a m e d a t ai si n t h eF Ka n dt h eP Ko ft h el i n k e dt a b l e si sn o td u p l i c t i o ni ti sa n e c e s s a r ym e t h o do fi m p l e m e n t i n gt h el i n k .

Meta'scommentaboutdatabasesremindsmeofthefactthattheschemaofthedatabaseandthecodethataccessthedatabasearetwo representationsofdatastructures.Ideally,boththecodeandthedatabaseschemawouldbedrivenoffthesamesourceofdatastructureinformation. ThisistheattractionofRuby'sActiveRecordandthereasonIhateHiberateandStruts.BothHiberateandStrutshaveduplicateinformationthat needstobeinsync.WithoutsomethinglikeXDoclettheywillgetoutofsyncandwillviolateDRY.SaS Merelyhopingtolearnwhat"DRY"is,Icame.Thethoughtinspiringphilosophicaldiscussionwastoomuch,merelytoread. Epidemiology(inshort,thestudyofdiseaseanddiseasedistributioninpopulations)promulgatestheideathatagivendiseasehassinglecausea rootcause.Insystems,RootCauseAnalysisinevitablytakesusbacktoadesignerrorandthisisoftentraceabletoanerrorintherequirements definition.(DatafromtheSoftwareEngineeringInstitute(SEI)atCarnegieMellonUniversity(CMU)showsanumberover60%,forthe percentageoferrorscausedwithinthestepspartofRequirementsDefinition.) Earliercomputerengineeringconcepts(say,early1980s)hadmaturedsufficientlythatstudents(andmanagers)mightbelievepeopleotherthan thosewhoareantisocialcanbeasgood(orbetter)thana"guru".Thecominggenerationofengineers/programmerswouldvaluewritingtheir ideaseveniftheydidn'tworkforIBM.Somemightevenplanahead.Thisalloweddesigntoavoidcircumstantialredundancy.TheDoDfunded workatCMUthatgaverisetotheSEIinthe1980srevealedthat"bestpractices"beginwith"planning"ofsomesort. Tosumupwhatcaneasilyoccupyvolumes:Weneedtolearnfromourmistakes.Thisrequiresconsciouseffortandtimecommitment,which makesitrare.Noacronymcanrepresenteveryproject,soacheatsheetmightsimplyreadas,"DRY".Thisisredundantwiththestartingpostbut Ididn'twriteitwhichmeansDRYhasnotbeenviolated.(Thoughthiscontrib/maybe/abitdry.)

c2.com/cgi/wiki?DontRepeatYourself

5/7

26/03/14

Dont Repeat Yourself

Kernel.package OnceAndOnlyOnceishardtoapplywhenconsumersappreciatePutThingsWhereYouLook.Andconsumerslookforeverythingeverywhere. Translation,"Whyisn'tthisemailalinkIcanclick.Youremailshouldbeonthecontactspage,theuserpage,thehelppage,andthehomepage." LeeLouviere


I tm u s tb ev i s a b l ee v e r y w h e r e .I tc a nl i v ei n o n l yo n ep l a c e .Av i e wi sn o tt h ed a t a .

CustomerrequeststrumpDRY.Ifsourcecodeontheinsideisdry,thenthoseemailclickerswillallusethesamecode,triviallypluggedinto severaldifferentviewlocationsPhlIp Hmm.Letmerephrase.PutThingsWhereYouLook(appliedtotheconceptofputtingthingseverywheretheusermightlook),mayleadto accidentallybreakingOnceAndOnlyOnce,andcanaccidentallybeviewedascontrasttoDontRepeatYourself.However,youshouldreally implementaprogramdataasuncoupledfromtheinterface.Don'tconfuseDRYtomeanthatinformationcanonlyhaveonelocationasopposedto onesource. Itaketheapproachtodesigndataandinterfaceasiftheywereseparateprograms,thenhavetheir"communication"derivedlast.ThatwayIensure thatdataisimplemented"native"tothemachinelanguageofsimplicity,andtheuserinterfaceisdesignedasmostconformingtohowtheuser woulduseitmeettheuserdemandofPutThingsWhereYouLookandthemyriadofdifferentarrangementsofthedatatoaccommodateeveryusers distinctwayofunderstandingdata.(EditMeneedabettertermhere,nativeisbad,communicationishorrible.)LeeLouviere Ifthisprincipleexistsatallitismorelikelytobecalled'eliminateneedlessredundancy'than'donotrepeatyourself.'A=Aisnotaredundant statement.Aisnotneedlessrepetition.A=BisnotthesameasA=AandAbyitselfdoesnotalwaysmeanA=Aifitistestandnotananalytic truth.Therearenumerousinstancesofclaimsofrepetitioninthediscussionabovewhereremovingoneoftheinstanceoftheallegedduplication willchangethemeaningandbehaviorofasystem.Ifyoucannotremoveoneoftheduplicateswithoutchangingmeaningitisnotduplication. Thenotionthatnormalizationrequiresduplicationbecausethekeysmustexistinbothtables,suggestthatremovingoneofthedubsispossiblebut itisnot. EvenIfIconcededthatduplicationisabettertermthanredundancythekeyisthatitisonlyneedlessduplicationthatmustbepurged.Theacidtest forneedless,forthosewhoseintuitionisnotasufficientguideisthis.Ifyoucan'tremoveitwithoutloosingfunctionalityitisnotneedless.
-A n n o n

OK,butalotoffunctionalityshouldstillbegeneralizedinmanycasessincethey'reverysimilar,andtherecouldbeabetter(moreelegant) implementationofit.Anonymous Sometimesmarketrulesdictatethechoiceofimplementationlanguage,whichcanmakeuseofDontRepeatYourselfextremelydifficult.Saythere's oneapplicationthatyouwanttodeployonmultipleplatforms,eachofwhichrequires(oratleastverystronglyprefers)codewritteninaparticular language.OneplatformrequiresObjectiveCee.Anotherplatformrequires100%pureJavaVirtualMachinebytecode.Athirdplatformrequiresthe useof100%verifiablytypesafeCIL(CommonLanguageRuntimebytecode).AfourthplatformrequiresJavaScript.ToachieveDRYunderthese constraints,onewouldhavetosomehowcreateaDomainSpecificLanguagethatcompilestoObjectiveC,compilestoJVMbytecode,compilesto safeCIL,andcompilestoJavaScript,andthenwritetheauthoritativeimplementationofthebusinesslogicinthatlanguage.Shouldeachcross platformapplicationprojectbeginbydesigningandimplementingaDSLasaworkaroundtoallowWriteOnceRunAnywheredespitethesemarket rules? (Forthosewhopreferconcreteexamples:iOSneedsObjectiveC,JavaMicroEditionphonesandJavaAppletbrowsersneedJavabytecode, WindowsPhone7andXboxLiveIndieGamesonXbox360needCIL,andFlash,HTML5browsers,andChromeWebStoreneedvariationsof EcmaScript.)DamianYerrick? DontRepeatYourself,butrepeatingothersisperfectlyacceptable:) Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem. ThissoundslikesomethingoutofOrwell's1984.Anystatementthatbeginswith"Everypieceofknowledgemusthave.."soundsliketheofficial propagandaofatotalitarianstatenotthefreeexchangeofideas.Perhapstheprinciplereallybeingexpressedhereis"It'smywayorthehighway." {"...andshouldpayme$130k/yrtopoliceandenforcethispolicy.":} IactuallywholeheartedlyagreewiththisandamprettysureitiswhyItakesolongtogetanythingdone.Ispendmoretimetryingnottoduplicate myselfandfindingcleverwaystoabstractoutthevariousduplicatedflowprinciplesinmyapplicationthanactuallysimplycoding.Sometimes whenIignoreruleslikeyouhavestated,Igetaninsaneamountofworkdone...veryquickly...andthenIworryifitismessy. RichardEllicott See:UnnecessaryHolography,OnceAndOnlyOnce,DuplicationRefactoringThreshold

c2.com/cgi/wiki?DontRepeatYourself

6/7

26/03/14

Dont Repeat Yourself

CategoryModelingLawsAndPrinciples,CategoryExtremeProgramming,CategoryPlanning,CategorySimplification EditTextofthispage(lasteditedMarch21,2014)orFindPagewithtitleortextsearch

c2.com/cgi/wiki?DontRepeatYourself

7/7

You might also like