Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
115-214
SchoolofComputerScience
PrinciplesofSoftwareConstruction:Objects,Design,andConcurrency
Designing(sub-)systems
Responsibilityassignment
CharlieGarrod MichaelHilton
215-214
Administrivia
• ReadingforToday:• UMLandPatternsChapter14,15,and16
• MidtermexamnextThursday(September28th)– Examreviewsession:Hamerschlag HallB103Wed7-9pm– PracticeExampostedonPiazza
• MuddiestPointFeedback
315-214
Homework4
• Threeparts,partAdueOct5th
• Designreviewmeetingnextweek
415-214
REVIEW:Sequenceandcommunicationdiagrams
515-214
Problem Space
Domain Model
SolutionSpace
Object Model
Our path toward a more formal design process
• Real-worldconcepts• Requirements,concepts• Relationshipsamongconcepts• Solvingaproblem• Buildingavocabulary
• Systemimplementation• Classes,objects• Referencesamongobjectsand
inheritancehierarchies• Computingaresult• Findingasolution
615-214
Artifactsofourdesignprocess
• Model/diagramtheproblem,defineobjects– Domainmodel(a.k.a.conceptualmodel)✓
• Definesystembehaviors– Systemsequencediagram– Systembehavioralcontracts
• Assignobjectresponsibilities,defineinteractions– Objectinteractiondiagrams
• Model/diagramapotentialsolution– Objectmodel
Understandingtheproblem
Definingasolution
715-214
Buildingadomainmodelforalibrarysystem
Apubliclibrary typicallystoresacollectionofbooks,movies,orotherlibraryitems availabletobeborrowedbypeoplelivinginacommunity.Eachlibrarymember typicallyhasalibraryaccount andalibrarycard withtheaccount’sIDnumber,whichshecanusetoidentifyherselftothelibrary.
Amember’slibraryaccountrecordswhichitemsthememberhasborrowedandtheduedate foreachborroweditem.Eachtypeofitemhasadefaultrentalperiod,whichdeterminestheitem’sduedatewhentheitemisborrowed.Ifamemberreturnsanitemaftertheitem’sduedate,thememberowesalatefeespecificforthatitem,anamountofmoneyrecordedinthemember’slibraryaccount.
815-214
Onedomainmodelforthelibrarysystem
915-214
Notesonthelibrarydomainmodel
• Allconceptsareaccessibletoanon-programmer• TheUMLissomewhatinformal
– Relationshipsareoftendescribedwithwords
• Real-world"is-a"relationshipsareappropriateforadomainmodel• Real-wordabstractionsareappropriateforadomainmodel• Iterationisimportant
– Thisexampleisafirstdraft.Someterms(e.g.Itemvs.LibraryItem,Accountvs.LibraryAccount)wouldlikelyberevisedinarealdesign.
• Aggregatetypesareusuallymodeledasclasses• Primitivetypes(numbers,strings)areusuallymodeledasattributes
1015-214
BuildadomainmodelforMonopoly
1115-214
BuildadomainmodelforMonopoly
Monopolyisagameinwhicheachplayerhasapiecethatmovesaroundagameboard,withthepiece’schangeinlocationdeterminedbyrollingapairofdice.Thegameboardconsistsofasetofproperties(initiallyownedbyabank)thatmaybepurchasedbytheplayers.
Whenapiecelandsonapropertythatisnotowned,theplayermayusemoneytobuythepropertyfromthebankforthatproperty’sprice.Ifaplayerlandsonapropertyshealreadyowns,shemaybuildhousesandhotelsontheproperty;eachhouseandhotelcostssomepricespecificfortheproperty.Whenaplayer’spiecelandsonapropertyownedbyanotherplayer,theownercollectsmoney(rent)fromtheplayerwhosepiecelandedontheproperty;therentdependsonthenumberofhousesandhotelsbuiltontheproperty.
Thegameisplayeduntilonlyoneremainingplayerhasmoneyandproperty,withalltheotherplayersbeingbankrupt.
1215-214
Understandingsystembehaviorwithsequencediagrams
• Asystemsequencediagram isamodelthatshows,foronescenarioofuse,thesequenceofeventsthatoccuronthesystem’sboundary
• Designgoal:Identifyanddefinetheinterfaceofthesystem– Twocomponents:Auserandtheoverallsystem
1315-214
Understandingsystembehaviorwithsequencediagrams
• Asystemsequencediagram isamodelthatshows,foronescenarioofuse,thesequenceofeventsthatoccuronthesystem’sboundary
• Designgoal:Identifyanddefinetheinterfaceofthesystem– Twocomponents:Auserandtheoverallsystem
• Input:Domaindescriptionandoneusecase• Output:Asequencediagramofsystem-leveloperations
– Includeonlydomain-levelconceptsandoperations
1415-214
Onesequencediagramforthelibrarysystem
Usecasescenario:Alibrarymembershouldbeabletouseherlibrarycardtologinatalibrarysystemkioskandborrowabook.Afterconfirmingthatthememberhasnounpaidlatefees,thelibrarysystemshoulddeterminethebook’sduedatebyaddingitsrentalperiodtothecurrentday,andrecordthebookanditsduedateasaborrowediteminthemember’slibraryaccount.
1515-214
Onesequencediagramforthelibrarysystem
Usecasescenario:Alibrarymembershouldbeabletouseherlibrarycardtologinatalibrarysystemkioskandborrowabook.Afterconfirmingthatthememberhasnounpaidlatefees,thelibrarysystemshoulddeterminethebook’sduedatebyaddingitsrentalperiodtothecurrentday,andrecordthebookanditsduedateasaborrowediteminthemember’slibraryaccount.
1615-214
BuildonesystemsequencediagramforMonopoly
Usecasescenario:Whenaplayerlandsonanunownedpropertyandhasenoughmoneytobuytheproperty,sheshouldbeabletobuythepropertyfortheproperty’sprice.Thepropertyshouldnolongerbepurchasablefromthebankbyotherplayers,andmoneyshouldbemovedfromtheplayertothebank.
1715-214
Formalizesystembehaviorwithbehavioralcontracts
• Asystembehavioralcontract describesthepre-conditionsandpost-conditionsforsomeoperationidentifiedinthesystemsequencediagrams– System-leveltextualspecifications,likesoftwarespecifications
1815-214
Asystembehavioralcontractforthelibrarysystem
Operation: borrow(item)
Pre-conditions: Librarymemberhasalreadyloggedintothesystem.Itemisnotcurrentlyborrowedbyanothermember.
Post-conditions: Logged-inmember'saccountrecordsthenewly-borroweditem,orthememberiswarnedshehasanoutstandinglatefee.Thenewly-borroweditemcontainsafutureduedate,computedastheitem'srentalperiodplusthecurrentdate.
1915-214
AsystembehavioralcontractforMonopoly
Operation: buy(property)
Pre-conditions: ?
Post-conditions: ?
2015-214
Distinguishingdomainvs.implementationconcepts
• Domain-levelconcepts:– Almostanythingwithareal-worldanalogue
• Implementation-levelconcepts:– Implementation-likemethodnames– Programmingtypes– Visibilitymodifiers– Helpermethodsorclasses– Artifactsofdesignpatterns
2115-214
Summary:Understandingtheproblemdomain
• Knowyourtoolstobuilddomain-levelrepresentations– Domainmodels– Systemsequencediagrams– Systembehavioralcontracts
• Befastand(sometimes)loose– Elideobvious(?)details– Iterate,iterate,iterate,…
• Getfeedbackfromdomainexperts– Useonlydomain-levelconcepts
2215-214
Artifactsofourdesignprocess
• Model/diagramtheproblem,defineobjects– Domainmodel(a.k.a.conceptualmodel)✓
• Definesystembehaviors– Systemsequencediagram✓– Systembehavioralcontracts✓
• Assignobjectresponsibilities,defineinteractions– Objectinteractiondiagrams
• Model/diagramapotentialsolution– Objectmodel
Understandingtheproblem
Definingasolution
2315-214
Object-orientedprogramming
• Programmingbasedonstructuresthatcontainbothdataandmethodspublic class Bicycle {private int speed;private final Wheel frontWheel, rearWheel;private final Seat seat;…
public Bicycle(…) { … }
public void accelerate() { speed++;
}
public int speed() { return speed; }}
2415-214
Object-OrientedDesign
• Object-OrientedDesign:“Afteridentifyingyourrequirementsandcreatingadomainmodel,thenaddmethodstothesoftwareclasses,anddefinethemessagingbetweentheobjectstofulfilltherequirements.”
• Buthow?– Howshouldconceptsbeimplementedbyclasses?– Whatmethodbelongswhere?– Howshouldtheobjectsinteract?– Thisisacritical,important,andnon-trivialtask
2515-214
Responsibilityinobject-orientedprogramming
• Data:– Privateorotherwiseencapsulateddata– Dataincloselyrelatedobjects
• Methods:– Privateorotherwiseencapsulatedoperations– Objectcreation,ofitselforotherobjects– Initiatingactionsinotherobjects– Coordinatingactivitiesamongobjects
2615-214
Responsibilities
• Responsibilitiesarerelatedtotheobligationsofanobjectintermsofitsbehavior.
• Twotypesofresponsibilities:– knowing– doing
• Doingresponsibilitiesofanobjectinclude:– doingsomethingitself,suchascreatinganobjectordoingacalculation– initiatingactioninotherobjects– controllingandcoordinatingactivitiesinotherobjects
• Knowingresponsibilitiesofanobjectinclude:– knowingaboutprivateencapsulateddata– knowingaboutrelatedobjects– knowingaboutthingsitcanderiveorcalculate
2715-214
Usinginteractiondiagramstoassignobjectresponsibility
• Foragivensystem-leveloperation,createanobjectinteractiondiagramattheimplementation-level ofabstraction– Implementation-levelconcepts:
• Implementation-likemethodnames• Programmingtypes• Helpermethodsorclasses• Artifactsofdesignpatterns
2815-214
Exampleinteractiondiagram#1
Usecasescenario:Alibrarymembershouldbeabletouseherlibrarycardtologinatalibrarysystemkioskand…
2915-214
Exampleinteractiondiagram#2
Usecasescenario:…andborrowabook.Afterconfirmingthatthememberhasnounpaidlatefees,thelibrarysystemshoulddeterminethebook’sduedatebyaddingitsloanperiodtothecurrentday,andrecordthebookanditsduedateasaborrowediteminthemember’slibraryaccount.
3015-214
Interactiondiagramshelpevaluatedesignalternatives
Createtwopossibleinteractiondiagrams:1. Solvingacryptarithm,assumingthatthecryptarithm classhas
responsibilityforsolvingitself2. Solvingacryptarithm,assumingthatthemainmethod(oradelegated
methodorclass)hasresponsibilityforsolvingthecryptarithm
3115-214
Goals,Principles,Guidelines
• DesignGoals– Desiredqualityattributesofsoftware– Drivenbycost/benefiteconomics– Examples:designforchange,understanding,reuse,…
• DesignPrinciples– Guidelinesfordesigningsoftware– Supportoneormoredesigngoals– Examples:Informationhiding,lowrepr.gap,lowcoupling,highcohesion,…
• DesignHeuristics– Rulesofthumbforlow-level designdecisions– Promotedesignprinciples,andultimatelydesigngoals– Example:Creator,Expert,Controller
• DesignPatterns– Generalsolutionstorecurringdesignproblems– Promotedesigngoals,butmayaddcomplexityorinvolvetradeoffs– Examples:Decorator,Strategy,TemplateMethod
• Goals,principles,heuristics,patternsmayconflict– Usehigh-levelgoalsofprojecttoresolve
Goals
Heuristics Patterns
Principles
X
3215-214
Heuristicsforresponsibilityassignment
• Controllerheuristic• Informationexpertheuristic• Creatorheuristic
Goals
Heuristics Patterns
Principles
3315-214
Thecontrollerheuristic
• Assignresponsibilityforallsystem-levelbehaviorstoasinglesystem-levelobjectthatcoordinatesanddelegatesworktootherobjects– Alsoconsiderspecificsub-controllersforcomplexuse-casescenarios
• Designprocess:Extractinterfacefromsystemsequencediagrams– Keyprinciples:Lowrepresentationalgapandhighcohesion
3415-214
Informationexpertheuristic
• Assignresponsibilitytotheclassthathastheinformationneededtofulfilltheresponsibility– Initialization,transformation,andviewsofprivatedata– Creationofcloselyrelatedorderivedobjects
3515-214
Responsibilityinobject-orientedprogramming
• Data:– Privateorotherwiseencapsulateddata– Dataincloselyrelatedobjects
• Methods:– Privateorotherwiseencapsulatedoperations– Objectcreation,ofitselforotherobjects– Initiatingactionsinotherobjects– Coordinatingactivitiesamongobjects
3615-214
Informationexpertheuristic
• Assignresponsibilitytotheclassthathastheinformationneededtofulfilltheresponsibility– Initialization,transformation,andviewsofprivatedata– Creationofcloselyrelatedorderivedobjects
• Designprocess:Assignmentfromdomainmodel– Keyprinciples:Lowrepresentationalgapandlowcoupling
3715-214
Usetheinformationexpertheuristic
• InHomework3,whatobjectshouldhavetheresponsibilitytosolveacryptarithm?
• Whatistherelevantinformation?
3815-214
Usetheinformationexpertheuristic
• InHomework3,whatobjectshouldhavetheresponsibilitytosolveacryptarithm?
• Whatistherelevantinformation?– Whoknowsthe#ofdigits(e.g.base10)inthecryptarithm?– Whoknowsthelettersofthecryptarithm?– Whocanevaluatethecryptarithm expressionstocheckforequality?
3915-214
Anotherdesignprinciple:Minimizeconceptualweight
• Labeltheconceptsforaproposedobject– Relatedtorepresentationalgapandcohesion
4015-214
Creatorheuristic:WhocreatesanobjectFoo?
• AssignresponsibilityofcreatinganobjectFootoaclassthat:– HasthedatanecessaryforinitializinginstancesofFoo– Contains,aggregates,orrecordsinstancesofFoo– CloselyusesormanipulatesinstancesofFoo
• Designprocess:Extractfromdomainmodel,interactiondiagrams– Keyprinciples:Lowcouplingandlowrepresentationalgap
4115-214
Usethecreatorheuristic
• InHomework3,whatobjectshouldhavetheresponsibilityforcreatingthepermutationgenerator?
4215-214
Object-levelartifactsofthisdesignprocess
• Objectinteractiondiagrams addmethodstoobjects– Caninferadditionaldataresponsibilities– Caninferadditionaldatatypesandarchitecturalpatterns
• Objectmodel aggregatesimportantdesigndecisions– Isanimplementationguide
4315-214
Creatinganobjectmodel
• Extractdata,methodnames,andtypesfrominteractiondiagrams– Includeimplementationdetailssuchasvisibilities
4415-214
4515-214
Createanobjectmodelforyourcryptarithm solver
4615-214
Summary:
• Object-levelinteractiondiagramsandobjectmodelsystematicallyguidethedesignprocess– Convertdomainmodel,systemsequencediagram,andcontractsto
object-levelresponsibilities
• Useheuristicstoguide,butnotdefine,designdecisions• Iterate,iterate,iterate…