introduction to software technology 4. grasp...
TRANSCRIPT
IntroductiontoSoftwareTechnology4.GRASPPatterns
KlausOstermann
EinführungindieSoftwaretechnik1
GRASPPatterns
EinführungindieSoftwaretechnik2
} ObjectDesign:} “Afteridentifyingyourrequirementsandcreatingadomainmodel,thenaddmethodstothesoftwareclasses,anddefinethemessagingbetweentheobjectstofulfilltherequirements.”
} Buthow?} Whatmethodbelongswhere?} Howshouldtheobjectsinteract?} Thisisacritical,important,andnon-trivialtask
GRASPPatterns
EinführungindieSoftwaretechnik3
} TheGRASPpatternsarealearningaidto} helponeunderstandessentialobjectdesign} applydesignreasoninginamethodical,rational,explainableway.
} Thisapproachtounderstandingandusingdesignprinciplesisbasedonpatternsofassigningresponsibilities
GRASP-Responsibilities
EinführungindieSoftwaretechnik4
} Responsibilitiesarerelatedtotheobligationsofanobjectintermsofitsbehavior.
} Twotypesofresponsibilities:} knowing} doing
} Doingresponsibilitiesofanobjectinclude:} doingsomethingitself,suchascreatinganobjectordoinga
calculation} initiatingactioninotherobjects} controllingandcoordinatingactivitiesinotherobjects
} Knowingresponsibilitiesofanobjectinclude:} knowingaboutprivateencapsulateddata} knowingaboutrelatedobjects} knowingaboutthingsitcanderiveorcalculate
Designpatternsinarchitecture} Apatternisarecurringsolutiontoastandardproblem,inacontext.
} ChristopherAlexander,professorofarchitecture…} Whyiswhataprofofarchitecturesaysrelevanttosoftware?
} “Apatterndescribesaproblemwhichoccursoverandoveragaininourenvironment,andthendescribesthecoreofthesolutiontothatproblem,insuchawaythatyoucanusethissolutionamilliontimesover,withouteverdoingitthesamewaytwice.”
Patternsinengineering} Howdootherengineersfindandusepatterns?
} Matureengineeringdisciplineshavehandbooksdescribingsuccessfulsolutionstoknownproblems
} Automobiledesignersdon'tdesigncarsfromscratchusingthelawsofphysics
} Instead,theyreusestandarddesignswithsuccessfultrackrecords,learningfromexperience
} Shouldsoftwareengineersmakeuseofpatterns?Why?} Developingsoftwarefromscratchisalsoexpensive
} Patternsareaformofreuseofsoftwaredesign
Definitionsandnames} Alexander:“Apatternisarecurringsolutiontoastandardproblem,inacontext.”
} Larman:“InOOdesign,apatternisanameddescriptionofaproblemandsolutionthatcanbeappliedinnewcontexts;ideally,apatternadvisesusonhowtoapplythesolutioninvaryingcircumstancesandconsiderstheforcesandtrade-offs.”
BasicPatternPrinciples
EinführungindieSoftwaretechnik8
} Patternsareneverinvented;theyarefound} theycodifyexistingtried-and-trueknowledge,idioms,andprinciples
} themorehonedandwidelyused,thebetter
} Patternsgiveanametoanidea!
Fred:"WheredoyouthinkweshouldplacetheresponsibilityforcreatingaSalesLineltem?IthinkaFactory."Wilma:"ByCreator,IthinkSalewillbesuitable."Fred:"Oh,right-Iagree."
GRASP} Namechosentosuggesttheimportanceofgraspingfundamentalprinciplestosuccessfullydesignobject-orientedsoftware
} AcronymforGeneralResponsibilityAssignmentSoftwarePatterns} (technically“GRASPPatterns”ishenceredundantbutitsoundsbetter)
} Describefundamentalprinciplesofobjectdesignandresponsibility
} Expressedaspatterns
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
InformationExpert
EinführungindieSoftwaretechnik12
} Problem:Whatisageneralprincipleofassigningresponsibilitiestoobjects?
} Solution:Assignaresponsibilitytotheinformationexpert} theclassthathastheinformationnecessarytofulfilltheresponsibility
} Startassigningresponsibilitiesbyclearlystatingresponsibilities!
} Forinstance,inaPOSapplicationastatementmightbe:“Whoshouldberesponsibleforknowingthegrandtotalofasale"?
InformationExpert
EinführungindieSoftwaretechnik13
} Whatinformationisneededtodeterminethegrandtotal?
} Saleistheinformationexpertforthisresponsibility.
InformationExpert
EinführungindieSoftwaretechnik14
} Whatinformationisneededtodeterminethelineitemsubtotal?
InformationExpert
EinführungindieSoftwaretechnik15
} Tofulfilltheresponsibilityofknowingandansweringitssubtotal,aSalesLineltemneedstoknowtheproductprice.
} TheProductSpecificationisaninformationexpertonansweringitsprice;therefore,amessagemustbesenttoitaskingforitsprice.
InformationExpert
EinführungindieSoftwaretechnik16
} Tofulfilltheresponsibilityofknowingandansweringthesale'stotal,threeresponsibilitieswereassignedtothreedesignclassesofobjects
InformationExpert:FinalDesign
EinführungindieSoftwaretechnik17
InformationExpert:Discussion
EinführungindieSoftwaretechnik18
} Expertusuallyleadstodesignswhereasoftwareobjectdoesthoseoperationsthatarenormallydonetotheinanimatereal-worldthingitrepresents} asaledoesnottellyouitstotal;itisaninanimatething
} InOOdesign,allsoftwareobjectsare"alive"or"animated,"andtheycantakeonresponsibilitiesanddothings.
} Theydothingsrelatedtotheinformationtheyknow.
InformationExpert:Discussion
EinführungindieSoftwaretechnik19
} Contraindication:Conflictwithseparationofconcerns} Example:Whoisresponsibleforsavingasaleinthedatabase?} AddingthisresponsibilitytoSalewoulddistributedatabaselogicovermanyclassesàlowcohesion
} Contraindication:Conflictwithlatebinding} Latebindingisavailableonlyforthereceiverobject} Butmaybethevariabilityoflatebindingisneededinsomemethodargumentinstead
} Example:Supportformultipleserializationstrategies
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
Creator
21
Problem: Assignresponsibilityforcreatinganewinstanceofsomeclass?
Solution:Determinewhichclassshouldcreateinstancesofaclassbasedontherelationshipbetweenpotentialcreatorclassesandtheclasstobeinstantiated.
Creator
22
} whohasresponsibilitytocreateanobject?} Bycreator,assignclassBresponsibilityofcreatinginstanceofclassAif} BaggregatesAobjects} BcontainsAobjects} BrecordsinstancesofAobjects} BcloselyusesAobjects} BhastheinitializingdataforcreatingAobjects
} wherethereisachoice,prefer} BaggregatesorcontainsAobjects
Creator:Example
23
WhoisresponsibleforcreatingSalesLineItemobjects?LookforaclassthataggregatesorcontainsSalesLineItemobjects.
Sale
datetime
SalesLineItem
quantity
ProductSpecification
descriptionpriceUPC
Described-by
*
Contains
1..*
Creator:Example
24
CreatorpatternsuggestsSale.Collaborationdiagramis
Creator
25
} Promoteslowcouplingbymakinginstancesofaclassresponsibleforcreatingobjectstheyneedtoreference
} Bycreatingtheobjectsthemselves,theyavoidbeingdependentonanotherclasstocreatetheobjectforthem
Creator:Discussion
EinführungindieSoftwaretechnik26
} Contraindications:} creationmayrequiresignificantcomplexity,suchas
} usingrecycledinstancesforperformancereasons} conditionallycreatinganinstancefromoneofafamilyofsimilarclassesbaseduponsomeexternalpropertyvalue
} Sometimesdesiredtooutsourceobjectwiring(“dependencyinjection”)
} Relatedpatterns:} AbstractFactory,Singleton,DependencyInjection
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
LowCoupling
28
Problem:Howtosupportlowdependency,lowchangeimpact,andincreasedreuse.
Solution:Assignaresponsibilitysothatcouplingremainslow.
WhyHighCouplingisundesirable
EinführungindieSoftwaretechnik29
} Couplingisameasureofhowstronglyoneelementisconnectedto,hasknowledgeof,orreliesonotherelements.
} Anelementwithlow(orweak)couplingisnotdependentontoomanyotherelements(classes,subsystems,…)} "toomany"iscontext-dependent
} Aclasswithhigh(orstrong)couplingreliesonmanyotherclasses.} Changesinrelatedclassesforcelocalchanges.} Suchclassesarehardertounderstandinisolation.} Theyarehardertoreusebecauseitsuserequirestheadditionalpresenceoftheclassesonwhichitisdependent.
LowCoupling
30
Howcanwemakeclassesindependentofotherclasses?changesarelocalisedeasiertounderstandeasiertoreuseWhohasresponsibilitytocreateapaymentandassociateittoasale?
LowCoupling
31
Twopossibilities:
1.Register
2.Sale
LowcouplingsuggestsSalebecauseSalehastobecoupledtoPaymentanyway(Saleknowsitstotal).
CommonFormsofCouplinginOOLanguages
32
} TypeXhasanattribute(datamemberorinstancevariable)thatreferstoaTypeYinstance,orTypeYitself.
} TypeXhasamethodwhichreferencesaninstanceofTypeY,orTypeYitself,byanymeans.} TypicallyincludeaparameterorlocalvariableoftypeTypeY,orthe
objectreturnedfromamessagebeinganinstanceofTypeY.
} TypeXisadirectorindirectsubclassofTypeY.} TypeYisaninterface,andTypeXimplementsthatinterface.
LowCoupling:Discussion
EinführungindieSoftwaretechnik33
} LowCouplingisaprincipletokeepinmindduringalldesigndecisions
} Itisanunderlyinggoaltocontinuallyconsider.} Itisanevaluativeprinciplethatadesignerapplieswhileevaluatingalldesigndecisions.
} LowCouplingsupportsthedesignofclassesthataremoreindependent} reducestheimpactofchange.
} Can'tbeconsideredinisolationfromotherpatternssuchasExpertandHighCohesion
} Needstobeincludedasoneofseveraldesignprinciplesthatinfluenceachoiceinassigningaresponsibility.
LowCoupling:Discussion
EinführungindieSoftwaretechnik34
} Subclassingproducesaparticularlyproblematicformofhighcoupling} Dependenceonimplementationdetailsofsuperclass} “FragileBaseClassProblem”[seeSEDesignLecture]
} Extremelylowcouplingmayleadtoapoordesign} Fewincohesive,bloatedclassesdoallthework;allotherclassesarejustdatacontainers
} Contraindications:Highcouplingtoverystableelementsisusuallynotproblematic
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
HighCohesion
36
Problem:Howtokeepcomplexitymanageable.
Solution:Assignresponsibilitiessothatcohesionremainshigh.
Cohesionisameasureofhowstronglyrelatedandfocusedtheresponsibilitiesofanelementare.
Anelementwithhighlyrelatedresponsibilities,andwhichdoesnotdoatremendousamountofwork,hashighcohesion
Highcohesion
37
} Classesareeasiertomaintain} Easiertounderstand} Oftensupportlowcoupling} Supportsreusebecauseoffinegrainedresponsibility
HighCohesion
38
Whohasresponsibilitytocreateapayment?
1.Register
looksOKifmakePayementconsideredinisolation,butaddingmoresystemoperations,Registerwouldtakeonmoreandmoreresponsibilitiesandbecomelesscohesive.
HighCohesion
39
GivingresponsibilitytoSalesupportshighercohesioninRegister,aswellaslowcoupling.
HighCohesion:Discussion
40
} Scenarios:} VeryLowCohesion:AClassissolelyresponsibleformanythingsinvery
differentfunctionalareas} LowCohesion:Aclasshassoleresponsibilityforacomplextaskinone
functionalarea.} HighCohesion.Aclasshasmoderateresponsibilitiesinonefunctionalarea
andcollaborateswithclassestofulfiltasks.} Advantages:
} Classesareeasiertomaintain} Easiertounderstand} Oftensupportlowcoupling} Supportsreusebecauseoffinegrainedresponsibility
} Ruleofthumb:aclasswithhighcohesionhasarelativelysmallnumberofmethods,withhighlyrelatedfunctionality,anddoesnotdotoomuchwork.
Problem:HighCohesionandViewpoints
EinführungindieSoftwaretechnik41 [Harrison&Ossher‘93]
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
Controller
43
Problem:Whoshouldberesponsibleforhandlinganinputsystemevent?
Solution:Assigntheresponsibilityforreceivingorhandlingasystemeventmessagetoaclassrepresentingtheoverallsystem,device,orsubsystem(facadecontroller)orausecasescenariowithinwhichthesystemeventoccurs(usecasecontroller)
Controller:Example
EinführungindieSoftwaretechnik44
Controller:Example
EinführungindieSoftwaretechnik45
} BytheControllerpattern,herearesomechoices:} Register,POSSystem:representstheoverall"system,"device,orsubsystem
} ProcessSaleSession,ProcessSaleHandler:representsareceiverorhandlerofallsystemeventsofausecasescenario
Controller:Discussion
EinführungindieSoftwaretechnik46
} Normally,acontrollershoulddelegatetootherobjectstheworkthatneedstobedone;itcoordinatesorcontrolstheactivity.Itdoesnotdomuchworkitself.
} Facadecontrollersaresuitablewhentherearenot"toomany"systemevents
} Ausecasecontrollerisanalternativetoconsiderwhenplacingtheresponsibilitiesinafacadecontrollerleadstodesignswithlowcohesionorhighcoupling} typicallywhenthefacadecontrollerisbecoming"bloated"withexcessiveresponsibilities.
Controller:Discussion
EinführungindieSoftwaretechnik47
} Benefits} Increasedpotentialforreuse,andpluggableinterfaces
} NoapplicationlogicintheGUI
} Dedicatedplacetoplacestatethatbelongstosomeusecase} E.g.operationsmustbeperformedinaspecificorder
} Avoidbloatedcontrollers!} E.g.singlecontrollerforthewholesystem,lowcohesion,lotsofstateincontroller
} Splitintousecasecontrollers,ifapplicable
} Interfacelayerdoesnothandlesystemevents
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
Polymorphism
49
Problem:Howtohandlealternativesbasedontypes?
Howtocreatepluggablesoftwarecomponents?Solution: Whenalternatebehavioursareselectedbasedonthetypeofanobject,usepolymorphicmethodcalltoselectthebehaviour,ratherthanusingif/casestatementtotestthetype.
Polymorphism:Example
EinführungindieSoftwaretechnik50
Polymorphism:Discussion
51
} Polymorphismisafundamentalprincipleindesigninghowasystemisorganizedtohandlesimilarvariations.
} Properties:} Easierandmorereliablethanusingexplicitselectionlogic} Easiertoaddadditionalbehaviorslateron} Increasesthenumberclassesinadesign} Maymakethecodelesseasytofollow
} Usingtheprincipleexcessivelyfor“future-proofing”againstyetunknownpotentialfuturevariationsisabadidea} Agilemethodsrecommendtodonosignificant“upfrontdesign”andaddthevariationpointonlywhentheneedarises
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
PureFabrication
53
Problem:Addingsomeresponsibilitiestodomainobjectswouldviolatehighcohesion/lowcoupling/reuse
Solution:Assignahighlycohesivesetofresponsibilitiestoanartificialorconvenienceclassthatdoesnotrepresentaproblemdomainconcept—somethingmadeup,tosupporthighcohesion,lowcoupling,andreuse.
PureFabrication:Example
54
} In the point of sale example support is needed to save Saleinstancesinarelationaldatabase.
} By Expert, there is some justification to assign thisresponsibilitytoSaleclass.
} However, the task requires a relatively large number ofsupporting database-oriented operations and the Sale classbecomesincohesive.
} The sale class has to be coupled to the relational databaseincreasingitscoupling.
} Saving objects in a relational database is a very general taskfor which many classes need support. Placing theseresponsibilities in theSaleclass suggests there isgoing tobepoor reuseor lotsofduplication inotherclasses thatdo thesamething.
PureFabrication:Example
55
} Solution:createanewclassthatissolelyresponsibleforsavingobjectsinapersistentstoragemedium
} ThisclassisaPureFabrication
} TheSaleremainswell-designed,withhighcohesionandlowcoupling
} ThePersistentStorageBrokerclassisitselfrelativelycohesive} ThePersistentStorageBrokerclassisaverygenericandreusable
object
PureFabrication:Discussion
56
} Thedesignofobjectscanbebroadlydividedintotwogroups:} Thosechosenbyrepresentationaldecomposition(e.g.Sale)} Thosechosenbybehavioraldecomposition(e.g.analgorithmobjectsuchasTOCGeneratororPersistentStorage)
} Bothchoicesarevaliddesigns,althoughthesecondonecorrespondslesswelltothemodelingperspectiveonobjects
} Ifoverused,itcanleadtoanon-idiomaticdesign,namelyaseparationofthecodeintodataandbehaviorasinproceduralprogramming} CouplingofdataandbehavioriscentraltoOOdesign
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
Indirection
58
Problem:Wheretoassignaresponsibility,toavoiddirectcouplingbetweentwo(ormore)things?Howtode-coupleobjectssothatlowcouplingissupportedandreusepotentialremainshigher?
Solution: Assigntheresponsibilitytoanintermediateobjecttomediatebetweenothercomponentsorservices,sothattheyarenotdirectlycoupled.
"Mostproblemsincomputersciencecanbesolved
byanotherlevelofindirection"
Indirection:Example
EinführungindieSoftwaretechnik59
Byaddingalevelofindirectionandaddingpolymorphism,theadapterobjectsprotecttheinnerdesignagainstvariationsintheexternalinterfaces
NineGRASPpatterns:} InformationExpert} Creator} LowCoupling} Controller} HighCohesion} Polymorphism} Indirection} PureFabrication} ProtectedVariations
ProtectedVariation
EinführungindieSoftwaretechnik61
Problem:Howtodesignobjects,subsystems,andsystemssothatthevariationsorinstabilityintheseelementsdoesnothaveanundesirableimpactonotherelements?Solution:Identifypointsofpredictedvariationorinstability;assignresponsibilitiestocreateastableinterfacearoundthem.Note:Thisisbasicallyjustanotherformulationoftheinformationhidingprinciple.
ProtectedVariation:Examples
EinführungindieSoftwaretechnik62
} Dataencapsulation,interfaces,polymorphism,indirection,andstandardsaremotivatedbyPV.
} VirtualmachinesarecomplexexamplesofindirectiontoachievePV
} Servicelookup:Clientsareprotectedfromvariationsinthelocationofservices,usingthestableinterfaceofthelookupservice.
} UniformAccessPrinciple} LawofDemeter} …
Literature
EinführungindieSoftwaretechnik63
} CraigLarman,ApplyingUMLandPatterns,PrenticeHall,2004} Chapter16+17+22introduceGRASP