Professional Documents
Culture Documents
DavidDuncan
November16,2012
Introduction
GRASP(GeneralResponsibilityAssignmentSoftware
Patterns)isanacronymcreatedbyCraigLarman to
encompassnineobjectorienteddesignprinciples
relatedtocreatingresponsibilitiesforclasses
Theseprinciplescanalsobeviewedasdesign
patternsandofferbenefitssimilartotheclassic
GangofFour patterns
GRASPisanattempttodocumentwhatexpert
designersprobablyknowintuitively
AllnineGRASPpatternswillbepresentedandbriefly
discussed
WhatisGRASP?
GRASP=GeneralResponsibilityAssignmentSoftware
Patterns(orPrinciples)
Acollectionofgeneralobjectedorienteddesign
patternsrelatedtoassigningdefiningobjects
OriginallydescribedasacollectionbyCraigLarman
inApplyingUMLandPatterns:AnIntroductionto
ObjectOrientedAnalysisandDesign,1st edition,in
1997.
Context(1of2)
ThethirdeditionofApplyingUMLandPatterns isthe
mostcurrentedition,publishedin2005,andisbyfar
thesourcemostdrawnuponforthismaterial
Larman assumesthedevelopmentofsometypeof
analysisartifactspriortotheuseofGRASP
Ofparticularnote,adomainmodelisused
Adomainmodeldescribesthesubjectdomainwithoutdescribing
thesoftwareimplementation
ItmaylooksimilartoaUMLclassdiagram,butthereisamajor
differencebetweendomainobjectsandsoftwareobjects
Context(2of2)
Otherwise,assumptionsarebroad:primarily,the
practitionerisusingsometypeofsensibleand
iterativeprocess
Larman choosestheUnifiedProcessbecauseitis:
Iterative
Flexibleandopen,integrateswellwithagileprocesses
PopularwithOOADprojects
ResponsibilityDrivenDesign
GRASPpatternsareusedtoassignresponsibilityto
objects
Assuch,theiruseresultsinaResponsibilityDriven
Design(RDD)forObjectOrientation(OO)
Contrastto(themoretraditional)DataDrivenDesign
Withthispointofview,assigningresponsibilitiesto
objectsisalargepartofbasicobjectdesign
WhyGRASP?
TraditionallyinObjectOrientedProgramming(OOP),object
designisglossedover
E.g.,thinkofnounsandconverttoobjects;thinkofverbsandconvert
tomethods
Oreven:Afterrequirementsanalysisandcreationofadomainmodel,
justcreateobjectsandtheirmethodstofulfillrequirements
(Oh....Ok.PoorinexperiencedOOdevelopers.)
UMLisjustalanguageitexpressesanOOdesignbutforthe
mostpartdoesnotprovideguidance
PerLarman,GRASPhelpsoneunderstandessentialobject
designandapplyreasoninginamethodical,rational,
explainableway.
DesignPatterns
Softwaredesignpatternswerelaunchedasa
conceptin1987byKentBeckandWard
Cunningham,baseduponChristopherAlexanders
applicationin(building)architecture
Coredefinition:anameddescriptionofaproblem
andacorrespondingreusablesolution
Ideally,thepatternadvisesonwhenitshouldbe
usedandthetypicaltradeoffs
Themostfamousdesignpatternsarethe23
describedbytheGangofFour (GoF)bookin1993
DesignPatternAdvantages
BoththeGoF patternsandGRASPpatternshave
notablebenefits:
Simplifying:providesanamed,generallyunderstood
buildingblock
Facilitatescommunication
Aidsthinkingaboutthedesign
Accelerateslearningtonothavetodevelopconceptsfrom
scratch
GRASPvs.GoF Patterns
GRASPpatternsareinawayevenmorefundamental
thantheGoF patterns
GRASPpatternsareequallywellreferredtoasprinciples,
whiletheGoF patternsarerarelyreferredtoassuch
Whilethenamingofbothtypesofpatternsis
important,itslessimportantfortheGRASPpatterns
Theconceptsaretrulywhatareimportant
AboutResponsibilities
Twotypesofresponsibilitiesforobjects:
Doing
Knowing
Knowingresponsibilitiesareofteneasilyinspiredbysoftware
domainobjects
E.g.,domainclassforaSalehasatimeattribute SaleclassinOO
designknowsitstimeaswell
ResultofmeetingthedomainmodelaimtohaveaLow
RepresentationalGap(LRG)
Doingresponsibilitiesoftencomefromearlymodeling
E.g.,eachmessageinaUMLinteractiondiagramissuggestiveof
somethingthatmustbedone
GRASPpatterns
TherearenineGRASPpatterns,likelysomealready
recognizableandsomenot:
Creator
InformationExpert(orjustExpert)
LowCoupling
Controller
HighCohesion
Polymorphism
PureFabrication
Indirection
ProtectedVariations
(NOTE:Theproblemandsolutionstatementsthatfolloware
almostverbatimfromLarman,exceptforaveryfewminor
attemptsataddingclarity.)
Creator
Problem:Whoshouldberesponsibleforcreatinganew
instanceofsomeclass?
Ifdonepoorly,thischoicecanaffectcoupling,clarity,encapsulation,
andreusability.
Solution:AssignclassBtheresponsibilitytocreatean
instanceofclassAifoneofthebelowistrue(themorethe
better).Ifmorethanoneoptionapplies,usuallypreferaclass
BwhichaggregatesorcontainsA.
BcontainsoriscomposedofA.
BrecordsA.
BcloselyusesA.
BhastheinitializingdataforAthatwillbepassedtoAwhenitis
created.
ThusBisanExpertwithrespecttocreatingA.
CreatorDiscussion
Thispatterngenerallyavoidsaddingcouplingtoa
design(whichisbadseeGRASPpattern#3).
Whencreationisacomplexprocessorvaries
dependinguponaninput,oftenyoullwanttocreate
usingadifferentclassimplementingtheGoF pattern
ConcreteFactoryorAbstractFactory.
InformationExpert
Problem:Whatisageneralprincipleofassigning
responsibilitiestoobjects?
Solution:Assignaresponsibilitytotheinformation
experttheclassthathastheinformationnecessary
tofulfilltheresponsibility.
InformationExpertDiscussion
Thisisgeneralprincipleandprobablythemostused
ofanyGRASPpattern.
Thisgenerallyiskeytoloosecouplingandhigh
cohesion,butnotalwaysso.
Imagineacasewhereitisbettertohandoffdatainorder
topreservealargefunctionaldivideandaidcohesiveness.
Weareimplicitlytalkingaboutinfoheldbya
softwareobject,butiftherearenotrelevant
softwareclasses,trythedomainmodel.
LowCoupling
Problem:Howtosupportlowdependency,low
changeimpact,andincreasedreuse?
Solution:Assignaresponsibilitysothatcoupling
remainslow.Usethisprincipletoevaluate
alternatives.
Couplingreferstoanytypeoftangibledependency
betweenelementsclasses,subsystems,systems,etc.
andisreferencedbyitsdegree:
Weak(low)isgood.
Strong(high)isbad.
LowCouplingDiscussion
Highercouplingcanleadto:
Moredifficultyinunderstanding
Changespropagatingexcessively
Moreobstaclestocodereuse
Lowercouplingoftengoeshandinhandwithhighercohesion(goodsee
GRASPpattern#5).
Considerthisprinciplewithevery designdecision.
Notethattoolittlecouplingwouldindicatesomethingiswrongwiththe
design,likelyincludinglowcohesion
InRDD(andreallyOO),theaimistohaveabroadnetworkoffocusedobjects
usingcommunicationtowardfulfillingtherequirementsinanorganized
fashion.
Themoreunstabletheclasscoupledto,themoreconcerningthe
connection
E.g.,consideralanguagesstandardlibraryvs.aclassacoworkerjustdefined
acoupledaysago.
Controller
Problem:WhatfirstobjectbeyondtheUIlayer
receivesandcoordinates(controls)asystem
operation?
Solution:Assigntheresponsibilitytooneofthe
followingtypesofclasses:
FaadeController:representstheoverallsystem,aroot
object,oradevicethatthesoftwareisrunning
Usecaseorsessioncontroller:representsausecase
scenariowithinwhichasystemeventoccurs(e.g.,addan
addressbookentry)
Theclasswouldtypicallybenamed<UseCaseName>Handler,
<UseCaseName>Coordinator,or<UseCaseName>Session
ControllerDiscussion
Acontrollerattemptstocoordinatethework
withoutdoingtoomuchofititself(again,guidedby
thedegreesofcouplingandcohesion)
Thekeywordisdelegation.
AneasyexampleofthisisthatUIobjectsshouldnt
performbusinesslogic;thereareotherclassesfor
that.
ThecontrollerintheModelViewController(MVC)
architectureiseffectivelythesamething.
This,oritsvariationModelViewPresenter,isfrequently
usedinwebapplications
HighCohesion
Problem:Howtokeepobjectsfocused,
understandable,andmanageable,andasaside
effect,supportLowCoupling?
Solution:Assignaresponsibilitysothatcohesion
remainshigh.Usethistoevaluatealternatives.
Cohesionreferstothefunctionalcohesionbetween
elements(classes,subsystems,systems,etc.),whichisa
measureofhowstronglyfocusedtheresponsibilitiesofan
elementare.
HighCohesionDiscussion
VerysimilartoLowCoupling
Oftenrelated(butnotalways)
Shouldbeconsideredinevery designdecision.
Lowercohesionalmostalwaysmeans:
Anelementmoredifficulttounderstand,maintain,or
reuse
Anelementmorelikelytobeaffectedbychange
Lowcohesionsuggeststhatmoredelegationshould
beused.
Polymorphism
Problem:Howtohandlealternativesbasedontype?
Howtocreatepluggablesoftwarecomponents?
Solution:Whenrelatedalternativesorbehaviors
varybytype(class),assignresponsibilitiesforthe
behaviorusingpolymorphicoperationstothe
typesforwhichthebehaviorvaries.
Polymorphicoperationsarethosethatoperateon
differingclasses
Donttestforthetypeoftheobjectanduseconditional
logictoperformvaryingstatementsbasedontype.
Polymorphism
Withrespecttoimplementation,thisusuallymeans
theuseofasuper(parent)classorinterface
Codingtoaninterfaceisgenerallypreferredandavoids
committingtoaparticularclasshierarchy.
Codelikethefollowingshouldraisearedflag!
Switch creatureType
Case batType: print Screech!
Case cowType: print Moooooo...
Case humanType: print Lets watch TV!
[...]
AlsoseeGRASPpattern#8,ProtectedVariations.
PureFabrication
Problem:Whatobjectshouldhavetheresponsibility,
whenyoudonotwanttoviolateHighCohesionand
LowCoupling,orothergoals,butsolutionsoffered
byExpert(forexample)arenotappropriate?
Solution:Assignahighlycohesivesetof
responsibilitiestoanartificialorconvenienceclass
thatdoesnotrepresentaproblemdomain
conceptsomethingmadeup,tosupporthigh
cohesion,lowcoupling,andreuse.
PureFabricationDiscussion
Inotherwords,gettingclassconceptsfromagooddomain
modelorreallifeobjectswontalwaysworkoutwell!
Anexampleofapossiblepurefabricationclass:
PersistentStorage
Mayverywellnotbeinthedomainmodel
Mayverywellnotmaptoareallifeobject
Butitmightbetheanswertoachieveourgoalsoflowcoupling/high
cohesionwhilestillhavingaclearresponsibility
ObservethatalloftheGoF designpatternsarepure
fabrications(oftenofmultipleclasses)
Indirection
Problem:Wheretoassignaresponsibility,toavoid
directcouplingbetweentwo(ormore)things?How
todecoupleobjectssothatlowcouplingis
supportedandreusepotentialremainshigher?
Solution:Assigntheresponsibilitytoanintermediate
objecttomediatebetweenothercomponentsor
servicessothattheyarenotdirectlycoupled.
Theintermediarycreatestheindirection.
IndirectionDiscussion
Oftenanindirectionintermediaryisalsoapure
fabrication.
ThePersistentStorage examplecouldverywellbean
indirectionbetweenaSaleclassandthedatabase.
TheGoF patternsAdapter,Bridge,Faade,Observer,
andMediatorallaccomplishthis.
Themainbenefitislowercoupling.
ProtectedVariations
Problem:Howtodesignelements(objects,
subsystems,andsystems)sothatthevariationsor
instabilityintheseelementsdoesnothavean
undesirableimpactonotherelements?
Solution:Identifypointsofpredictedvariationor
instability;assignresponsibilitiestocreateastable
interfacearoundthem.
ProtectedVariationsDiscussion
Inthesolutioninterface ismeantinthegeneralsense;butyoulloften
wanttouseaninterfaceprogrammingconstruct(inJava,forexample)to
implementthesolution!
Benefits:
EasytoextendfunctionalityatPVpoints
Lowercoupling
Implementationscanbeupdatedwithoutaffectingclients
Reducesimpactofchange
Verysimilartotheopenclosedprincipleortheconceptofinformation
hiding(notthesameasdatahiding)
InLarmans firstedition,wastheLawofDemeter,butProtected
Variationsisamoregeneralizedexpression
Novicedeveloperstendtowardbrittledesigns,intermediatedevelopers
tendtowardoverlyfancyandflexible,generalizedones(inways that
nevergetused).Expertdesignerschoosewithinsight.
ForMoreInformation
FormoreonGRASP,itshardtobeatthedepthofLarmans
text:
Larman,Craig.ApplyingUMLandPatterns:AnIntroductiontoObject
OrientedAnalysisandDesignandIterativeDevelopment.Third
edition,PrenticeHall,2005.
ItiswellwrittenandthereisalsosubstantialmaterialonUML,agile,GoF
designpatterns,aprojectlevelperspective,andmore.
IfGRASPdoesntstrikeachord,therearealternative
approachestothegeneralquestionofHowdoIcreatean
OOdesignusingobjects? Forexample:
WirfsBrock,RebeccaandMcKean,Alan.ObjectDesign:Roles,
Responsibilities,andCollaborations.AddisonWesleyProfessional,
2002.
Evans,Eric.DomainDrivenDesign:TacklingComplexityintheHeartof
Software.AddisonWesleyProfessional,2003.
Conclusion
GRASPprovidesamapofconsiderationstoprovide
strongguidanceforanOOdesigner
Butatthesametime,GRASPstillleavesalotofroom
tothedesignerandcreatingagooddesignisstillan
art!
TakingalookatGRASPandreallyApplyingUML
andPatternsisagoodbetforOOdesignerswho
knowthebasicsofOOPbutarestillinexperienced