Introduction to Design Patterns: Why they're worth learning

文章推薦指數: 80 %
投票人數:10人

the writings of Alexander Shvets on refactoring.guru. The author has created an amazing resource that I quote heavily throughout this post. (He ... Asdevelopers,we’reconstantlylearning-andthere’salottolearningeneralbecausethetechindustryisbroadandfast-paced.Wewanttohaveallthemainbasescoveredsothatwecanbereadyforanysituation.Weoftenhearaboutdesignpatternsandhowtheycanenableustowritewell-architectedsoftwareusingobject-orientedprogramming.Ifyou’relikeme,youmightfilethatawayasasetofconceptstolearnlater.Ifiledthemintothe“important,butnoturgent”(quadranttwoofEisenhower’smatrix)category.Ofcourse,therearemanytopicstolearnthatarerequiredforustodoourjob.Sodesignpatternsmightnotmakeittothetopofyourprioritylist-whereitemsliketesting,frameworks,CI/CD,oradozenotherthingslive. Iwasalwaysintriguedbydesignpatterns,butaswithlearninganythingnew,Iwasinthedarkaboutalotofthings.First,Ididn’tknowwhyIshouldlearnthem.Ididn’tknowwhattheyare.“Aretheybestpractices,SOLIDprinciples,architectureguides,orwhat?”Iwouldask.Idon’tknowexactlyhowtheycanhelpme(besidessimplybeingfamiliar).Naturally,Ididn’thaveaclearlearningpath-Ididn’tknowhowIshouldlearnthemorifit’stherighttimeformetolearnthem.Whataretheprerequisites?WhatmaterialshouldIuseandhowdoIavoidbeingscattered?HowdoIputthemintopractice? NowthatI’vespentoverayearlearningdesignpatterns,Iwantedtosharemyjourneyandhopefullyansweralloftheabovequestions.IwentfromfeelingscatteredamongstresourcesIhaphazardlyencounteredlikeblogpostsandvideos,toseekingoutsomebooks,andencounteringafewpatternsatwork.Whenmymentormadeafewfantasticrecommendations,Iwasofftotheraces: thewritingsofAlexanderShvetsonrefactoring.guru.TheauthorhascreatedanamazingresourcethatIquoteheavilythroughoutthispost.(Healsohasbooksavailable.) waystoputdesignpatternsintopractice (Also,shout-outtoanawesomevideoseries-ChristoperOkhraviondesignpatterns-whichreallyhelpedmegetmyinitialbearings.) ThegoalofthisarticleistoprovideaguidethatIwould’velovedwhenIfirststartedmyjourney.Itprovidesclarificationon: exactlywhatdesignpatternsareandthetypesofproblemstheycansolve whatdesignpatternsaren’tandthetypesofproblemsthattheydon’tsolve Finally,afteryourmentalschemasareprimed,Iprovidemuch-neededmotivationtotakethefirststeps. howlearningdesignpatternshelpyousolvesoftwareproblemsingeneral howlearningdesignpatternswillbuildintuitionsoyoucaneasilyspottheseproblemsfromahigh-level Inanotherpost,IprovideanumberofresourcesthatI’vefoundhelpfulwhilelearningandasuggestedcurriculum. Let’sbeginbymakingthementalspacefordesignpatternsbydiscussingwhattheyare. WhatDesignPatternsare YoumayhaveheardofthebookDesignPatterns:ElementsofReusableObject-OrientedSoftwarea.k.a.the“GangofFour”(“GoF”)book(wherethefourauthorsarethe“GangofFour.“)Using“patternlanguage”adaptedfromabookaboutbuildings,thegangcameupwith23designpatterns.(Readmorehereandhere.) Asmentioned,I’llbeheavilyquotingthewritingsofAlexanderShvetsonrefactoring.guruthroughoutthispost.Here’sanintroductoryquotefromthesite: “Designpatternsaretypical(2)solutionstocommonproblemsin(1)software(object-oriented)design.Eachpatternislikea(3)blueprintthatyoucancustomizetosolveaparticulardesignprobleminyourcode.” Let’sdigintothreekeyparts(inbold)ofthisstatement. (1)“software(object-oriented)design” Tosaydesignpatternsencompassallof“softwaredesign”istoobroad,inmyopinion.Iprefertothinkofthemas“object-oriented(OOP)designpatterns”becausetheyaremostoftentaughtandimplementedthisway.(Caveat:it’snotimperativetouseclasses(etc)toimplementdesignpatterns.)Forthesakeofargument,let’ssay“software”canbebrokenintofivelevels:1.ground-levelbyte-code.2.language(idiom)3.feature(businesslogic).4.architecture.5.deployment.Thelevelsbestsuitedtoapplyingdesignpatternsarethelanguage(idiom)level,thefeaturelevel,andarchitecturelevels. Thefirstlevel(byte-code)isn’ttoorelevant.Ifwe’retalkingaboutthedesignofthetoolsthatcreatebyte-codefromsourcecode,thenwe’rediscussingthethirdlevelofsoftware.(ToolsI’mfamiliarwithincludegulpandwebpack-“plugin”systemswhichmayusetheTemplateMethod,Strategy,orotherpatternstoimplementthem.) Theapplicabilityatthesecondlevel(language,idiom)islimitedsincelanguageidiomsdependonthebestpracticesofthatlanguage.Somepatternsthatapplyatthislevelare: https://refactoring.guru/design-patterns/memento-Herewe’reguidedtowardsvariouswaysofimplementingthepatternusingnestedclasses,anintermediateinterface,andanevenstricterencapsulation.Noneoftheseimplementationschangesthefundamentalnatureofthepattern,butthisguidanceisuseful. https://refactoring.guru/design-patterns/prototype-Thispatternmayhelpusunderstandprototype-basedlanguages(includingJavaScript.) https://refactoring.guru/design-patterns/iterator-Thispatternmayhelpusunderstanditeratorsprovidedbyalanguage(exampleinJavaScript.) Togetmorefamiliarwithlanguageidiomsfordesignpatterns,besuretocheckouthttps://refactoring.guru/design-patterns/exampleswhichhasillustrationsofallthepatternsinmanylanguages! Theapplicabilityatthethirdlevel(feature)isthe“sweetspot.”Theyshineatencapsulatingbusinesslogic,memorymanagement,servercalls,andmuchmore.Forexample,ifIknowthatIneedawaytogetmultipleobjectsthatsolvevariationsofaproblem,IcanusetheFactoryMethodpattern.IfIwanttobeabletooptionallywrapobjectswithextrafunctionalityasneeded,IcanusetheDecoratorpattern.IfIneedtosetupachainofclasseswhereoneoptionallypassestheresulttothenext,theChainofResponsibilitypatterncouldhelp.Thepointbeing,most(ifnotall)ofthepatternscanaidinfeatureimplementation. Designpatternsarealsoveryapplicabletothefourth(architectural)levelofsoftware.WemayusetheAdapterpatterntomorphdataintoaformatwecanusebetweenaModellayerandaControllerlayer.WecouldimplementtheProxypatterntoauthenticatewritestoadatabase. Finally,thefifth(deployment)levelcanbenefitfromdesignpatternsiftherearecodecapabilitiesfordeploymentarchitectures.Inthiscase,seelevelfourabove. (IwouldliketomentionmoreadvancedpatternshereincludingMicrosoftcloudpatternsand12factor.Theseresources,linkedattheendofthisarticle,guideustoimplementingbestpracticeslikeisolatingpiecesofasystem,makingcertainpiecesstateless,etc.) (2)“solutionstocommonproblems” Eachofthe23patternsattempttosolveoneormoreissuesthatfrequentlyariseincodebases.Herearesomeexamplesdescribedwiththeirrespectivepatterns: Cognitivecomplexity.Object-orientedprogrammingiscommonlycriticizedformakingittooeasytooveruseinheritancewherecompositionwouldbesuperior.Theprimarydangerofinheritanceiscreatingtoomanysubclasses.Thesesubclassescontainvariationsbasedonasmallpropertythatchanges-somethingthatshould’vebeenisolatedandpassedintoasingleclass.AddressedbytheBridge,Command,Strategy,State,andotherpatterns.(The“too-many-combinations”problemresultsfromCartesianproducts.ChristopherOkhravidetailsitinhisBridgepatternvideoandothervideos.) Needingtocontrolaccesstoanobject.Forinstance,you’reusingathird-partylibraryandyouonlywanttouseafewmethodsofitsAPI(andotherswouldbedetrimentalforyourapplication.)TheFacadepatternwouldworkwellinthiscase.OtherpatternsthataddressaccessissuesincludeSingleton,andProxy. Needingtobuildanobjectinpieces.TheBuilderpatternaddressesthisbeautifullybygivingusmethodsthatwecanopt-intotocreateanobject.TheTemplateMethodpatternissimilarbutallowsustooverrideoromitcertainstagesofanalgorithm. ConservingRAM.TheFlyweightpatternallowsustocachesharedpartsofobjectsandletotherpartsbeunique.(The“access-control”patternsmentionedabovealsoaddresscaching.) Makinganundo/redostackavailable.AddressedbytheMementoandCommandpatterns. Ahugebenefittohavingacatalogofcommonproblemsistheycomewithdescriptivelanguagetoillustratetheproblem.OneofmyfavoriteexamplesistheVisitorpattern.Theproblemiswehaveanetworkofnodesandweneedtotraverseandprocessthem.Insteadofhardcodinginalgorithmsforanodeclass,we“visit”thenodewithaspecialclass(Visitor)thathasaccesstoanode’smethodsanddataasneeded.Thenodethatgetsvisitediscommonlycalled“element”(whichisgeneric)butyoucanthinkofitasa“visitee”tocompletetheessentialpairofthepattern. (3)“blueprintsyoucancustomize” Ratherthanthinkingofdesignpatternsasoff-the-shelfsolutions,thinkofthemasguidanceonsplittingproblemsintosmallerpiecesandhavingthesepiecesinteract.Youcancustomizeapatternbyaddingfunctionalitythatisn’tincludedinitsdescription.Forexample,youmightaddautilitymethodforanIteratorsothatyoucanquicklyretrieveitemsfromagivenlist.Anotherwayofcustomizingapatternisbyomittingpiecesyoudon’tneed.AnexampleofthisistheBuilderpatternwhichhasa“director”classyoucanoptintousing. WhatDesignPatternsaren’t(andadditionalconsiderations) Theyaren’tanautomaticenforcementofbestpractices Designpatternscertainlyaren’tasilverbullet.Yourusageofthemdoesn’tnecessarilymakeyourcodebetter,moretestable,moremaintainable,oreasiertocomprehend.Theseconcernsare“foundational”tothesoftwareyouwriteanddesignpatternsmayormaynotaddressthem. WeoftenhearofS.O.L.I.D.principles-bestpracticesthatincreasethequalityofoursoftware.Forexample,the“S”ofSOLIDistheSingle-responsibility-principle-preferfunctionswithasingleresponsibility.Functionalprogrammingprinciplescanhelpusachievethisaswell.Forexample,alwayscreatingfunctionsthatdon’tmutatetheirinputandhaveadeterministicoutputbasedonitsinput.Sincedesignpatternsare“blueprints,”thislanguage-specificlevelstuffwillbeuptoyouduringimplementation.(Theirproperusecertainlywillincludebestpractices.) Theycan’tsolveeverypossibleproblem “Designpatternsbuildonthefoundationslaidbysolidanalysisofsoftwaredevelopment.(1)Youwillnotfindapatternthatsolveseveryproblemyouencounter.Someproblemsaresimplyintractableandunmanageable.Otherproblemsmayhaveasolution,buttherearenowidelyknownpatternstosolvethechallengeathand.Indeed,thismaybeanopportunityforyoutomakeamentalnotebydocumentingapatternyouinvent,discoverordocumentasyousynthesizeexistingpatternstocreatenewpatterns.”https://www.gofpatterns.com/design-patterns/module7/limitations-of-design-patterns.php Let’ssayyou’re“intheweeds”ofdevelopingafeature.Youmayhaveyourclassesneatlyarranged,butthenfindyourselfneedingtocreateextralayersandconsiderationstosuccessfullyusethepatternsorcorrectlyimplementbusinesslogic.Manyofthepatternsinvolvea“client”objectwhichisanespeciallyloosedescriptionofhowthecoreobjectsinteract.Writingclientimplementationsisalwaysonthedeveloperandyoumayfindyourselfwithoutaguideonhowtoarchitectyourspecificfeature. Complexity Inmanycases,thetradeoffofimplementingadesignpatternandkeepingthecodestraightforwardmightnotbeworthit.Acaveatwithmanypatternsis“Thecodemaybecomemorecomplicatedthanitshouldbe,sincealotofnewinterfacesandclassesareintroducedalongwiththepattern.”(https://refactoring.guru/design-patterns/abstract-factory,https://refactoring.guru/design-patterns/flyweight,andmore) Ifyou’vedecidedtooptintothecomplexitytradeoff,youmayfindthatthecomplexitybreedsmorecomplexity.Forexample,youmayneedtoaddadditionallayersoflogictoallownewobjectstotalktoeachother.There’snowmorecodeandmorethatcangowrong.(Seeflockingruleshttps://jamiewright.dev/2019/02/04/refactoring-flocking-rules/) There’samiddle-groundapproachthatweshouldconsiderbeforechangingexistingcodetoutilizeadesignpattern.Refactoring.gurufeaturesarefactoringsectionthatidentifiesproblemsonamoregranularlevel.Whilesomeofthesolutionsincludedesignpatterns,manyofthemdon’tneedtogothatfar. IncorrectUsage Finally,asmentionedinhttps://refactoring.guru/design-patterns/criticism,it’seasyenoughtousepatternsbadlyorincorrectly.Doingsomayleadtoinefficientordifficulttounderstandcode.Youmightaswellstartoverwithoutapatterninthesecasesuntilit’sclearhowtocorrectlyimplementone.(Example-anon-globalSingletonmayincreaseperformancebutdeceivedeveloperswholaterworkonthecode) MotivationforlearningDesignPatterns Thereareafewextrinsicallymotivatingreasonstolearndesignpatterns.We’llbeablesuccessfullyanswerinterviewquestionsaboutthem.Wecanparticipateinorleadteamdiscussionsinvolvingthem.Additionally,knowledgeofthemstrengthensourobject-orientedprogramming(OOP)andgeneralprogrammingskills. Personally,thesereasonsdidn’tinitiallymotivatemetoputineffortbeyondreadingafewarticleshereandthere.IwanttobeexcitedaboutwhatIlearn.Beingintrinsicallymotivatedallowsanythingyoulearnto“stick”better.(Moreaboutextrinsicandintrinsicmotivation.)Let’sstartwiththisusefuloverviewrefactoring.guru: “Designpatternsareatoolkitoftriedandtestedsolutionstocommonproblemsinsoftwaredesign.Evenifyouneverencountertheseproblems,knowingpatternsisstillusefulbecauseit(1)teachesyouhowtosolveallsortsofproblemsusingprinciplesofobject-orienteddesign.Designpatterns(2)defineacommonlanguagethatyouandyourteammatescanusetocommunicatemoreefficiently.Youcansay,“Oh,justuseaSingletonforthat,”andeveryonewillunderstandtheideabehindyoursuggestion.Noneedtoexplainwhatasingletonisifyouknowthepatternanditsname.”https://refactoring.guru/design-patterns/why-learn-patterns Let’sdigintoafewkeyparts(inbold)ofthisstatement. (1)“teachesyouhowtosolveallsortsofproblems” Beingabletothinkintermsofinteractionsbetweenobjectsisincrediblybeneficialforsolvingproblemsbywayofcreatingwell-abstractedcode. Asyoubecomemorefamiliarwithdesignpatterns,youcananticipatecommonproblemsthatarise.Wesawaslewofproblemexamplesinthe“solutionstocommonproblems”section.Knowinglyornot,you’veprobablyusedtheStrategy,Facade,Adapter,orotherpatternsbefore. Thereareverypopularexternallibrariesthatuseandallowthedevelopertoutilizedesignpatterns.Understandingdesignpatternswillhelpyoumoreeasilyunderstandhowtheywork.Examples: SubscriptionmethodsinReduxuseapub-subObserversystem ReactlifecyclemethodsandDatabasehooks(seetheSequelizeORMforexample)utilizetheTemplateMethodpattern https://github.com/davidkpiano/xstateisastatemachine-Statepattern YoucanusetheDecoratorpatterndirectlyinJavaScriptifyouconfigureyourapplicationusingexperimentaltooling.Here’sanexampleinReact.HigherOrderComponents(HOCs)achieveasimilareffectwithfunctioncomposition.ReadaboutthemintheofficialReactdocsandhere. Wementionedbestpracticesbefore,andIbelievewhenimplementedcorrectly,designpatternsencouragecreationofclean,well-architectedcode.ManyofthedesignpatternswerebornoutofmotivationtoimplementS.O.L.I.D.principles. TheVisitorpatternencouragestheOpen/ClosedPrincipleandtheSingleResponsibilityPrinciple TheFactoryMethodpatternencouragestheOpen/ClosedPrinciple\andthe_SingleResponsibilityPrinciple_ TheCompositepatternencouragestheOpen/ClosedPrinciple Seethepros/conssectionsoftheabovelinksandmanyoftheotherpatterns. (2)“defineacommonlanguage” Enablingandimprovingcommunicationforyourselfandbetweendevelopers,inmyopinion,isverymotivating.Intheearlier“solutionstocommonproblems”section,webroughtupafewcommonproblemsandnamesofpatternsthataddressthem.Havingtheseasasharedvocabularynotonlyhelpsyouconveyyourthoughtstoothers,itclarifiesyourinternalvoicewhileyou’reworkingonyourown. Theterminologyusedthroughoutthestudyofthetopicusuallybeginswithananalogytosomethingyoucanunderstandoutsideofsoftware.Oncetheanalogybecomesconcretizedwithcodeexamples,yourabilitiestocommunicateonthehigherdesignlevelwillincrease.Learningthroughanalogieswillbeageneralmentalbenefit.You’llunderstandtheseconceptsmoredeeplybecauseyou’llbeabletorelatethemtoconceptsoutsideofprogramming.(Moreabouttakingadvantageoftheseanalogiesinthe“howtolearn”section.) Buildingintuitionandcreativity Designpatternscanbethoughtofas“distilledexperience”ofpastengineers.Theyprovideacatalogofproblemsthathavecomeupsomanytimesbefore.We’reinaprivilegedpositiontoavoidreinventingthewheeland,bestofall,tobuildintuitionforsolvingtheseproblems. Weimmenselybenefitfromlearningthisrepertoireofpre-builtsolutions.Studyingwiththegoalofinternalizingthemisanimportantstepforbuildingintuition.Onceinternalized,youmayhaveaconversationwithyourteamwhileplanningtheimplementationofafeature.Youcouldrecallapatternandhavea“lightbulb”moment.You’reabletoseethepatterninyourmind,rememberitsname,andeasilyspeaktoitsassociatedterminology.Nowyoucanconfidentlydiscusshowitwouldbehooveusto“usetheStrategypatterntoabstractthealgorithmoutofthefunction.Wecanseethattheselinesofthefunctionhavethealgorithmhard-codedin.Thismakesitimpossibletoreuseourloopingstrategytogathertheprocessedelements.TheStrategypatternsolvesthis.” Havingthisintuitioncanunlockcreativity.Designpatternsprovideawell-definedstructurethatwecancreativelyworkwith.Tobreaknewground,wemightopttogo“backwards”byseekingproblemswithasolutioninmind,reversingtheusualproblem-firstroutine.Thisallowsustosolveproblemsinanewwayandreinforceourproblem-solvingschemas. Othercreativeapproachesarealsoopenedup.Beingabletorecognizewhereyoucanvarypatternsallowsyoutoseethem(andotherconstructs)morefluidly.Thesevariationsmayevenleadtocomingupwithanewtypeofpatternaltogether! Conclusion Ofcourse,thisisn’tnecessarilytheendofthetopic.WecangowellbeyondtheGang’s23designpatterns. CloudDesignPatterns|Microsoft-“Thesedesignpatternsareusefulforbuildingreliable,scalable,secureapplicationsinthecloud.Eachpatterndescribestheproblemthatthepatternaddresses,considerationsforapplyingthepattern,andanexamplebasedonMicrosoftAzure.MostofthepatternsincludecodesamplesorsnippetsthatshowhowtoimplementthepatternonAzure.However,mostofthepatternsarerelevanttoanydistributedsystem,whetherhostedonAzureoronothercloudplatforms.” The12FactorAppMethodology-“Inthemodernera,softwareiscommonlydeliveredasaservice:calledwebapps,orsoftware-as-a-service.Thetwelve-factorappisamethodologyforbuildingsoftware-as-a-serviceapps”… https://techbeacon.com/app-dev-testing/top-5-software-architecture-patterns-how-make-right-choice https://en.wikipedia.org/wiki/Applications_architecture#Patterns https://martinfowler.com/bliki/DomainDrivenDesign.html LearningPaths Inmynextpost,IprovideanumberofresourcesthatI’vefoundhelpfulwhilelearningandasuggestedcurriculum.←RandomMusicGeneratorsNews2021-01-30HowtoLearnDesignPatterns→



請為這篇文章評分?