44
Designing Objects with Designing Objects with Responsibilities Using several specific design principles to guide OO design decisions.

Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Designing Objects with Designing Objects with Responsibilities

Using several specific design principles to guide OO design decisions.

Page 2: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

ChallengeChallengeOld-school advice on OOD

“Aft id tif i i t d ti d i d l th dd “After identifying your requirements and creating a domain model, then add methods to the appropriate classes, and define the messages between the objects to fulfill the requirements.”

New school advice: there are consequences to:New-school advice: there are consequences to:where we place methodsthe way objects interact in our designspecific principles can help us make these decisionsspecific principles can help us make these decisions

Note: This is not UML!UML is a notation

“ h l d l f f d l d llLarman: “The critical design tool for software development is a mind well educated in design principles.”

Page 3: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Recall: The big pictureRecall: The big pictureObject design is part of the larger modeling effort

some inputs to modeling:What’s been done?How do things relate?How much design modeling to do, and how?What is the output?Domain models, SDDs

some outputs from modeling:object design (UML diagrams – interaction, class, package)UI sketches and prototypesp ypdatabase modelssketches of reports and prototypes

Page 4: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Design of objectsDesign of objectsResponsibility-driven design (RDD)

What are an object’s responsibilities?What are an object s responsibilities?What are an object’s roles?What are an object’s collaborations?

The term is important:The term is important:We are initially trained to think objects in terms of data structures and algorithms (attributes and operations)RDD shifts this by treating objects as having roles and responsibilities

Objects then become:service providersinformation holders

d llcoordinators, controllersinterfaces, etc.

Page 5: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

What is an object responsibility?What is an object responsibility?Doing

d i thi it lf ( ti bj t f i l l ti )doing something itself (creating an object; performing a calculation)initiating action in other objectscontrolling and coordinating activities in other objects

KKnowingknowing about private encapsulated dataknowing about related objectsknowing about things it can derive or calculate

Responsibilities vary in “granularity”big (hundreds of classes); example: “provide access to relational databases”g p psmall (one method); example: “create an instance of Sale”

Page 6: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Wh t i bj t ll b ti ?What is an object collaboration?Assumption:

ibiliti i l t d b f th dresponsibilities are implemented by means of methodsthe larger the granularity of responsibility, the larger the number of methodsthis may entail an object interacting with itself or with other objects

Th fTherefore:fulfilling responsibilities requires collaborations amongst different methods and objects

“Low representational gap”:RDD is a metaphor“Objects” are modeled as similar to persons / systems with responsibilities“Community of collaborating responsible objects”

Page 7: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

A couple of parenthetical comments“Responsibility” here implies “non-interference”

This is idealized (i.e., in the real world this is not necessarily true in boundary cases)However it is suitable enough for object designg j g

Suitable for “programming-in-the-large”As opposed to “programming-in-the-small”Th l d ffThis is a qualitative difference:

mass of detailsamount of communicationthis become overwhelming

“Practical” as opposed to “theoretical”

Page 8: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

GRASPGRASPCraig Larman’s methodical approach to OO designI In essence:

a tool to help apply responsibilities to OOD designdesigned (and meant to be used as) methodical, rational, gexplainable techniques

They are “patterns of assigning responsibilities”Note: the use of “pattern” here is slightly different from some p g ythat intended by the GoF book

Recognizes that “responsibility assignment” is something already do:already do:

UML interaction diagrams are about assigning responsibilities

Page 9: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

A bit more about “pattern” terminology“Patterns” as applied to architecture:

i t d b Ch i t h Al dinvented by Christopher Alexandercontext that of a “pattern language” for designing spaces used by humans

Cl i d i f fClassic design patterns for softwareinvented by the Gang of Four (GoF) (Gamma, Johnson, Helm, Vlissides)

“Patterns” is now a rather “loose” termConferences exist to look at patternshttp://hillside.net/plop/2005/p p p

Larman has a special meaning for his GRASP patterns

Page 10: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

What is a GRASP pattern?What is a GRASP pattern?A named and well-known problem/solution pair

General enough to be applied to new contexts

Specific enough to give advice on how to apply it

Especially important for novel situations

Also comes with a discussion of:trade-offsimplementationsvariations

Page 11: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Specifically GRASPSpecifically GRASPDefines nine basic OO principles

b i b ildi bl k f OO d ibasic building blocks for OO designsMeant to be “pragmatic”Meant to be a “learning aid”:g

aids naming the group of ideasaids in presenting insight of ideasaids in remembering basic classic design ideasaids in remembering basic, classic design ideas

Also intended for combination with:a development process (UP)

i i l h (RDD)an organizational metaphor (RDD)a visual modeling notation (UML)

Page 12: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

The Nine GRASP PatternsThe Nine GRASP Patterns1. Creator 6. Polymorphism

2. Information Expert

3. Low Coupling

7. Pure Fabrication

8. Indirection

4. Controller

5. High Cohesion

9. Protected Variations

Page 13: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

1 GRASP Creator1. GRASP CreatorObject creation is one of the Problem: Who should be responsible for

creating a new instance of some class?

Sale

most common OO activities(However, set aside for now such concerns as “Factory M h d” “Ab F ”)

creating a new instance of some class?

Example: Who is responsible for creating “SalesLineItem”?

time

Contains

1

Method” vs. “Abstract Factory”)“Creator” principle is meant to help us achieve:

l lSales

LineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by*

1..*

1

low couplingincreased clarityincreased encapsulationincreased reusabilityincreased reusability

Recall: We also have a Register class floating about.g g

Page 14: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Jargon alert: terms and definitionsJargon alert: terms and definitions

coupling: the degree to which each program module relies on other modulesprogram module relies on other modules

cohesion: a measure of how well thecohesion: a measure of how well the operations in a module work together to provide a specific piece of functionality

encapsulation: synonym for “information hiding”

reusability: likelihood a segment of structured code can be used again to add new functionality with slight or noadd new functionality with slight or no modification

Page 15: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

1 GRASP Creator1. GRASP CreatorProblem statement:

Who should be responsible for creating a new instance of some class?

Solution:So ut o :Assign class B the responsibility to create an instance of class A if one of these is true (& the more the better)…i B “contains” or compositely aggregates Ai. B contains or compositely aggregates A.ii. B records Aiii. B closely uses A.i B has initializing data for A (i e B is an Expert with respect to iv. B has initializing data for A (i.e., B is an Expert with respect to

creating A).

Page 16: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

1 GRASP Creator1. GRASP CreatorSale Sale will contain many Who is responsible for

creating SalesLineItem”?time

Product

Contains

1..*

1

ySalesLineItem objects

Creator GRASP pattern t S l i bj t th t

creating SalesLineItem ?

SalesLineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by* 1suggests Sale is one object that could fulfill this responsibility.

Consequences:: Register : Sale

makeLineItem(quantity)

S l Li Icreate(quantity)

qmakeLineItem becomes a method in Sale.

we capture this decision in our : SalesLineItemcreate(quantity) we capture this decision in our UML design-model diagrams

Page 17: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

GRASP patterns give you moreGRASP patterns give you more…Each of these patterns comes with:

“di i ” tia “discussion” sectiona “contraindication” sectiona “benefits” section “ l t d tt i i l ” tia “related patterns or principles” section

Important!these patterns provide advice on assignment of responsibilitiespatterns may conflict in their advicethere we must exercise some judgment in applying these patternsthe extra sections help us with this

This is not mechanical work!

Page 18: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

1 GRASP Creator1. GRASP CreatorDiscussion:

i t t i t t l li (i t i f d th t intent is to support low coupling (i.e., creator is found that already needs to be connected to created object)initializing data is sometimes an indicator of a good Creator

bj t t t h l i tsome object constructors have complex signatureswhich objects have the information needed to supply parameter values for such constructors?

ContraindicationsContraindicationscreation can be complex (recycled instances, creating an instance from a family of similar classes)may wish to use Factory Method or Abstract Factory instead in may wish to use Factory Method or Abstract Factory instead in these cases

Page 19: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

1 GRASP Creator1. GRASP CreatorBenefits:

low coupling has already been mentionedwhy is this good?

R l t d tt i i lRelated patterns or principles:Low CouplingFactory Method and Abstract FactoryFactory Method and Abstract FactoryWhole-Part pattern: defines aggregate objects that support encapsulation of components

Page 20: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Reality CheckReality Check

Page 21: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

2 GRASP Information Expert2. GRASP Information ExpertProblem statement: What is a general principle of assigning responsibilities to objects?

Recall: design model may end up very large (hundreds of classes and methods)and methods)If assignment of responsibilities is well chosen, result is an easy to understand system

Solution:Assign a responsibility to the information expertThis expert is the class that has the information needed to fulfill the responsibility

Page 22: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Key idea:Key idea:

(“Cl St t t” R l ) St t(“Clear Statement” Rule): Start assigning responsibilities by clearly stating the responsibility.

Page 23: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

2 GRASP Information Expert2. GRASP Information ExpertNextGEN POS will end up with lots

f f lIf there are relevant classes in the design

Sale

of functionalityOne small part of this is class that knows the grand total of a sale

“Clear Statement” rule could

If there are relevant classes in the design model, then look there first for classes…

time

Contains

1

Clear Statement rule could transform this into:

“Who should be responsible for knowing the grand total of a sale?”

SalesLineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by*

1..*

1

Which class of objects has the information needed to determine the total?

… otherwise look into the Domain Model in order to use or expand its representations to suggest the creation of appropriate classessuggest the creation of appropriate classes

Page 24: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

2 GRASP Information Expert2. GRASP Information ExpertSale

tiSale

time...

getTotal()

:Salet = getTotal

new method

time

SalesLineItem

ProductDescription

d i tiDescribed-by*

Contains

1..*

1

1

quantitydescriptionpriceitemID

new method

Page 25: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

2 GRASP Information Expert2. GRASP Information Expert

SaleSale

time...

getTotal()1 *: st = getSubtotal: Salet = getTotal lineItems[ i ] :SalesLineItem

SalesLineItem

quantity

getSubtotal():ProductDescription

1.1: p := getPrice()

ProductDescription

descriptionpriceitemID

Sale

time

1

getPrice()new methodSales

LineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by*

Contains

1..*

1

Page 26: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

CommentCommentNotice how the initial assignment of responsibilities drove th d ithe design:

Result is the identification of several new methodsInteraction diagram helped us capture the resultg p pClass model entities are also modified

Also notice the degree of delegation“ S b l” ( “ P i ” d “ Q i ” l “getSubtotal” (vs. “getPrice” and “getQuantity” to supply a multiplication operation)

Page 27: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

2 GRASP Information Expert2. GRASP Information ExpertRead text for full details on pattern’s:

Di iDiscussionContraindications (important!)

Benefits:Information encapsulationlow couplingbehavior is distributed across classes (i.e., high cohesion)( , g )

Related Patterns:Low couplingHigh cohesionHigh cohesion

Page 28: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

3 GRASP Low Coupling3. GRASP Low CouplingProblem:

d How can our design supportlow dependency?low change impact?increased reuse?

Solution:Assign a responsibility so that coupling remains low.Assign a responsibility so that coupling remains low.Use this principle to evaluate alternative assignment of responsibilities.

Page 29: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Key idea:Key idea:

Coupling affects global d di b d i i bunderstanding, but decisions about

placing responsibility must be made more locally, usually by choosing from amongst alternatives.f o a o gst alte atives.

Page 30: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

ExampleExampleNextGen POS: dealing with Payments“What object should be responsible for associating Payments with Sales?” Three objects appear to be involvedj pp

Real-world domain: Register records a Payment (Creator?)Also in real-world: A Register also records Sales.

Page 31: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

ExampleExample

Suppose we apply our two previous GRASP patterns like so:pp pp y p p(Creator) Suggests Register as a candidate for creating Payments.

(Information Expert) Register knows about Payments, and therefore associates these with Salesthese with Sales

Resulting interaction diagram appears below

: Register p : PaymentmakePayment() 1: create()

:Sale2: addPayment(p)

Page 32: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

ExampleExample

Recall: Our GRASP pattern is to be applied to alternatives.: p pp .

Another approach:(Creator) Suggests Sales creates Payments ( ) gg y

: Register :SalemakePayment() 1: makePayment()

:Payment

1.1. create()

Page 33: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Evaluating AlternativesEvaluating Alternatives

: Register p : PaymentmakePayment() 1: create()

: Register :SalemakePayment() 1: makePayment()

1.1. create()

:Sale2: addPayment(p)

Which design choice results in lower coupling?

:Payment

Page 34: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Kinds of CouplingKinds of CouplingOften applied to “types” or “classes”

Class X has an attribute referring to Class Y instanceClass X objects call on the services of a Class Y objectClass X has methods referencing instances of Class Y (i.e., g ( ,parameters, local variables of Class Y)Class X is a direct or indirect subclass of Class YY is an interface and Class X implements itY is an interface, and Class X implements it

Note:All of these are needed at some pointpWe are not trying to eliminate coupling, but rather make careful choices

Page 35: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Important contra indicatorImportant contra-indicatorThere is a least one set of objects and classes to which we

t ll d t b hi hl l dmust allow our code to be highly-coupledJava libraries (i.e., javax.swing, java.util) etc.C libraries.NET libraries

Key features permitting this:h blthese are stable

they are widespread

Page 36: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

4 GRASP Controller4. GRASP ControllerProblem:

h f b b d h l d d What first object beyond the UI layer receives and coordinates (“controls”) a system operation?

Solution:Assign responsibility to a class based on one of the following:

class is “root object” for overall system (or major subsystem)a new class based on use case namea new class based on use case name

Page 37: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

ContextContextThis usually is applied to the actions recorded in our SSDs

system events generated by some GUI d t it t th GUI j t t b t UI lwe do not write to the GUI just yet, but assume some UI layer

Therefore we do not have “window”, “view” or “document” classesdocument classes

Be very careful here as we are so tied to GUIs when visualizing applicationsGUI is meant to “delegate” tasks to system

Page 38: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Example (NextGen POS)Example (NextGen POS)

Records sale of

ProductCatalog

ProductDescription

Contains

1..*

Records-sale-of

1

11

Ledger

Records-

1

Which class of object should be responsible for receiving the enterItem() system event message?

ItemStore

SalesLineItem

Stocks

*

Houses

Used-by

*Describes

*

Contained in

1..*

0..1

Logs1

1 1..*

Records-accounts-

for

1

system event message?

Register? POSSystem?

These represent overall “system” “root object”

RegisterSale

Houses

1..*

Captured-on

Contained-in Logs-completed

*1

0..1 1

system , root object , device, or subsystem.

ProcessSaleHandler?ProcessSaleSession?(these would be new)

CashPayment CashierCustomer

Paid-by Is-for 3 Works-on

1

1

1

1

1

1(these would be new)

These represent a receiver or handler of all system events of a use case scenariocase scenario.

Page 39: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Example NextGen POSExample NextGen POSRegister

...

System

endSale()enterItem()Here are the two basic endSale()

enterItem()makeNewSale()makePayment()

makeNewReturn()enterReturnItem(). . .

()makeNewSale()makePayment()

makeNewReturn()enterReturnItem(). . .

Here are the two basic alternatives.

system operations discovered during system behavior analysis

allocation of system operations during design, using one facade controller

(And how do we choose from amongst them?)

ProcessSaleHandler

...

endSale()enterItem()

System

endSale()enterItem()makeNewSale()makePayment()

HandleReturnsHandler

...

enterReturnItem()makeNewReturn()

makeNewSale()makePayment()

y ()

enterReturnItem()makeNewReturn(). . .

allocation of system operations during design, using several use case

t ll

. . .

controllers

Page 40: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

CautionsCautionsA balance must be striked between having too many controllers and too few

More common problem: too few (i.e., “bloated ll ”controllers”)

Example:l ll l f ll f dsingle controller classes for all events (façade)

controller performs many of the events itself rather than delegate workgcontroller maintain a lot of state about the system (e.g., variables and attributes)

Page 41: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

5 GRASP High Cohesion5. GRASP High CohesionProblem:

k b dHow can we keep objects in our designfocused?understandable?manageable?

Solution:Assign a responsibility so that cohesion remains high.Assign a responsibility so that cohesion remains high.As with low coupling, use this evaluate alternatives to placing responsibilities in objects

Page 42: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Signs of Low CohesionSigns of Low CohesionClasses that do too many unrelated things or which do too much workworkSuch classes are:

hard to comprehendhard to reusehard to maintaindelicate in that any change elsewhere in the system requires many changes in hi lthis class

In general:the greater the granularity of classes, the lower the cohesionbut we do not want to go to the other extreme (i.e., lots and lots of classes, each doing one trivial thing)

Page 43: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Compare and contrastCompare and contrast: Register : Sale

addPayment( p )

p : Paymentcreate()makePayment()

(Yet again) What class should be responsible for creating a class instance and associating it with a

: Register S l

Sale?

: Register : Sale

makePayment()

: Paymentcreate()

makePayment()

We have two options WhichWe have two options. Which shows both high cohesion and low coupling?

Page 44: Designing Objects with Responsibilities · 8/1/2013  · ya tool to help apply responsibilities to OOD design ydesigned (and meant to be used as) methodical, rational, explainable

Contra indicatorsContra-indicatorsSimple people-management issues

Large class maintained by a single programmer

PerformanceDi ib d Distributed systemsAny place where the overhead of invoking an operation is a significant proportion of performing the operationg p p p g p