GRASP: Patterns for assigning responsibility · • Codified patterns, principles and idioms can be...
Transcript of GRASP: Patterns for assigning responsibility · • Codified patterns, principles and idioms can be...
GRASP: Patterns for assigning responsibilityassigning responsibility
chapter18
1
Chapter Objectives
• Learn about design patterns
• Learn how to apply five GRASP patterns
2
Building Collaboration diagrams
• System Design: how the system will do whatwe decided it should do• We must identify software classes and assign responsibilities.• For each operation contract we build a collaboration diagram.• We work through the postconditionstate changes and design • We work through the postconditionstate changes and design message interactions to satisfy the requirements.• In doing so, we assign responsibilities to objects.• Poor choices lead to hard to implement, maintain, reuse, or extend system design
3
Building Collaboration diagrams, cont
• Interaction diagrams are one of the most important artifacts created in OOAD.
• The skillful assignment of responsibilities that occurs while creating collaboration diagrams is very while creating collaboration diagrams is very important.
• The amount of time and effort spent on their generation, and the careful consideration of responsibility assignment, should absorb a significant percentage of the design phase.
• Codified patterns, principles and idioms can be applied to improve the quality of their design. 4
Responsibilities and methods
• Responsibilities are related to the obligations of an object in terms of its behavior.
• Two types of responsibilities:1. Doing responsibilities : 1. Doing responsibilities :
– Doing something itself (on its attributes).– Initiating actions in other objects (by calling functions in them).– Controlling and coordinating activities in other objects (receiving data
from one object an send them to another object). 2- Knowing responsibilities :
– Private encapsulated data.– Related objects.– Things it can derive or calculate .
5
Responsibilities and methods, cont
• Responsibilities are assigned to objects during design.
• Example:Saleresponsibilities
1. Printing itself (doing) 1. Printing itself (doing) 2. Knowing its date
• Responsibilities related to knowing(who know who) are often detected from conceptual modelfrom the attributes and associations
6
Responsibilities and methods, cont
• responsibility ≠ method• A responsibility is not the same thing as a method, but
methodsare implemented to fulfill responsibilities.– For example, “provide access to a relational database”may involve
dozens of classes and hundreds of methods, whereas “create a Book Entry” may involve only one or few methods.Entry” may involve only one or few methods.
• Methods either act alone or collaborate with other methods and objects.– For example, Salehas a responsibilitynamed print. To fulfill this
responsibility, the Sale may collaboratewith other objects, such as sending a message to SaleLineItemobjects asking them to printthemselves.
7
Responsibilities and Collaboration Diagrams
:Sale :SaleLineItem1*:[for each] sli:=next()print ()
8
1*:[for each] sli:=next()print ()
sli:SaleLineItem2:print()
Methods asking collaborationwith other objects to print themselves
Responsibility of Sale objects is to printthemselves
GRASP
• Describe fundamental principles of object design and responsibility.
• Acronym for General Responsibility Assignment Software PatternsSoftware Patterns
• GRASP is expressed as patterns.
• Patterns are problem/solution pairs that guide in assigning responsibilities by giving advice in how to apply it in varying circumstances
9
Pattern Name: Name
Solution: Proposed solution of a problem
Problem it solves: describes the problem that this pattern solves
GRASP
• There are 5 basic GRASP patterns:1. Expert.
2. Creator.
3. Low coupling.3. Low coupling.
4. High cohesion.
5. Controller.
10
1- The Expert Pattern
• Problem: What is the most basic principle of assigning responsibilities to objects?
• Solution: Assign a responsibility to the information expert class – i.e. the class that has the information necessary to fulfill the responsibility is given the responsibility .
• Start by clearly stating the responsibility:• Start by clearly stating the responsibility:• Example:
– In POST, who should be responsible for knowing the grand total of the sale?
– By expert pattern, we should look for that class that has the information needed to determine the total.
11
Expert Example
12
Expert Example, cont
• Step 1:What information is needed to determine the grand total?
• It is necessary to know about all the SaleLineItems instancescomposing the Sale and their subtotals.
• Only Saleobject knows the information about SaleLineItemsit contains. So by Expert pattern, the Sale objectis the information expert and should be one of its responsibilities to compute the sale total.be one of its responsibilities to compute the sale total.
• Collaboration diagram so far:
13
Expert Example, cont
• Step 2:To determine the SaleLineItemsubtotals, what information is needed?- We need SaleLineItem.quantityand Productspecfication.price.- The SaleLineItem object knows its quantityand its associated Productspecfication (which contains the price). -Thereby by Expert pattern, SaleLineItemobjectshould determine the -Thereby by Expert pattern, SaleLineItemobjectshould determine the subtotalas it is the information expert.
• Collaboration diagram so far:
14
T:=getTotal()sli:SaleLineItem
2: st:=subtotal():Sale
:SaleLineItem
1*:[for each] sli:=next()
Expert Example, cont
• Step 3:Finally, how the SaleLineItem will compute its subtotal?
• It should know its item pricethrough ProductSpecfication.
• Thus, the ProductSpecfication objectis the information expert of the item price; therefore a message must be sent to it from of the item price; therefore a message must be sent to it from SaleLineItem object asking for the price.
• Thus, ProductSpecfication must have a method called price() that returns the item price.
15
Expert Example, cont
T:=getTotal()
sli:SaleLineItem2: st:=subtotal()
:SaleFrom step2
16
:ProductSpecification
2.1: p:=price()
:SaleLineItem
1*:[for each] sli:=next()From step1
step2
From step3
Expert Example, cont
• Class Responsibilities
Class Responsibility
Sale Knows sale total
17
Sale Knows sale total
SaleLineItem Knows line item subtotal
ProductSpecification Knows product price
2- The Creator Pattern
• Problem: Who should be responsible for creating a new instance of some class?
• The creation of objects is one of the most common activities in OO system. If assigned well, the design can support low coupling, encapsulation and reusability.
• Solution: Assign class Bthe responsibility to create an • Solution: Assign class Bthe responsibility to create an instance of class Aif one or more of the following is true:– B aggregatesA objects.– B containsA objects.– B recordsinstances of A objects.– B has the initializing datathat will be passed to A when it is created
(thus B is an Expert with respect to creating A).
18
2- The Creator Pattern
• Thus B is called a creator of A objects.• If more than option applies, prefer a class B
which aggregates or contains class A.Example:•• In POST, who should be responsible for
creating a SaleLineItem instance?• By Creator, we should look for the class that
aggregates, contains, records, closely uses, or has initializing data for SaleLineIteminstances.
19
Creator Example
• From the conceptual model, a Salecontains (aggregates) many SaleLineItemobjects.
• By creator, Sale is a good candidate to have the responsibility of creating SaleLineItem instances.
• A method called makeLineItemis defined in Saleclass to create the SaleLineItemobjects (1….*).
• A method called makeLineItemis defined in Saleclass to create the SaleLineItemobjects (1….*).
2020
makeLineItem(quantity)
:SaleLineItem
1: create(quantity)
:Sale
Sale
DateTime
getTotal()makeLineItem()
A new method is added to the Sale class
3-Low Coupling Pattern
• Coupling:it is a measure of how strongly one element is connected to, has knowledge of, or relies upon other elements.
• A class with high coupling depends on many other classes(libraries, tools).
21
(libraries, tools).
• Problemsbecause of a design with high coupling:– Changes in related classes force local changes.
– Harder to understand in isolation; need to understand other classes.
– Harder to reuse because it requires additional presence of other classes.
3Low Coupling Pattern, cont
• Problem: How to support low dependency, low change impact and increased reuse?
• Solution: Assign a responsibility so that coupling remains low.
• Example: In POST, we need to create a Payment
22
• Example: In POST, we need to create a Payment instance and associate it with the Sale.
• Which class should be responsible for this? (creator)
Payment POST Sale
Low coupling example
- Since aPOSTrecordsa Payment, by Creator, a POSTshould be responsible for creating a Paymentinstance p.
- The POSTinstance then sends an addPaymentmessage to the Sale, passing the new Paymentinstance as parameter.
- This solution couples POSTwith the knowledge of Paymentclass. 23
:Sale
makePayment( ) 1: create():POST p:Payment
2: addPayment(p)
Low coupling example, cont
• Another alternative is to make Saleclass responsible for creating a Paymentand associateit with the Sale.
makePayment( ) 1: addPayment():POST :Sale
• In both cases, eventually, Salehas to be coupled withthe knowledge of Payment� first designhas an extra coupling. While second design does not increase coupling.
• We may face Low coupling vs. Creator tradeoff. 24
:Payment
1: addPayment()
1.1: create()
3- Low Coupling Pattern, cont
• There is no specific measurement for coupling, but in general, classes that are generic and simple to reuse have low coupling.
• Coupling will lead to highly interacting classes.classes.
• There will always be some coupling among objects, otherwise, there would be no collaboration.
• A subclass is strongly coupled to its superclass. The decision to derive a subclass from superclass must be carefully considered as it produces a strong form of coupling. 25
3- Low Coupling Pattern, cont
• Benefits:– Understandability: Classes are easier to understand
in isolation
– Maintainability: Classes aren’t affected by changes – Maintainability: Classes aren’t affected by changes in other components
– Reusability: easier to grab hold of classes
26
4- High cohesion pattern
• Cohesion: (functional cohesion)it is a measure of how strongly related and focused the responsibilities of a class are.
• A class with low cohesion does many unrelated activities or does too much work.
• A class with high cohesion has highly related responsibilities, and does not do a large amount of work by itself.
27
• A class with high cohesion has highly related responsibilities, and does not do a large amount of work by itself.
• Problemsbecause of a design with low cohesion:– Hard to understand.– Hard to reuse.– Hard to maintain.
4- High cohesion pattern, cont
• Problem: How to keep complexity manageable?• Solution: Assign a responsibility so that cohesion remains
high.
Example:
28
Example:• In POST, we need to create a Paymentinstance and
associate it with the Sale. Which class should be responsible for this?
Payment POST Sale
makePayment( ) 1: create():POST p:payment
Since a POST records a payment, by Creator, a POSTshould be responsible for creating a payment instance.
High cohesion example
29
: Sale2: addPayment(p)
• This solution gives the responsibility of creating paymentwith POST who records it (creator).• We add more unrelated responsibilities to POST, thus it became incohesive. •We can not let POST instance do all the work related to it.
makePayment( ) 1: addPayment():POST :Sale
- Another alternative is to make Sale responsible for (take the job from POST) creating a Payment and associate it with it.
High cohesion example, cont
30
: Payment
makePayment( ) 1: addPayment()
1.2: create()
•This solution supports high cohesion and low coupling� more desirable than Creator.
4- High cohesion pattern, cont
• Benefits:– Understandability: Clarity & ease of
comprehension.
– Maintainability: Maintenance and enhancement is – Maintainability: Maintenance and enhancement is easier.
– Complements Low Coupling
31
5- The Controller Pattern
• Problem: Who should be responsible for handling an input system event?
• A system event is a high level system generated by an external actor; it is an external input event (which is found in the SSD).
• They are associated with system operations.
32
• They are associated with system operations.• For a cashier (external actor) using an a POST presses the
EndSale button, he is generating a system event indicating “the sale has ended”.
• A controller is a non-user interface object responsible for handling a system event.
• A controller defines the method for the system operation.
• Solution: Assign the responsibility for receiving or handling a system event message to a class representing one of the four following choices:– Represents the overall system. (façade controller)– Represents the overall organization. (façade controller)– Represents something in the real world that is active (the role of a person)
5- The Controller Pattern, cont
33
– Represents something in the real world that is active (the role of a person) that might be involved in the task. (role controller)
– Represents an artificial handler of all system events of a use case. (use-case controller) use the name <Use case name>Handler
• Each use case has one controller for its operations (1 use case = 1 controller for all system events in the same use case)
• Note that windows, applets, etc. typically receive events and delegate them to a controller. They are NOT controllers.
5- The Controller Pattern, contExample:• In POSTsystem, there are several system operations.• Who should be the controller for the system events such
as enterItem? There are many choices:
System
endSale()enterItem()makePayment()
enterItem():POST Overall System (façade controller)
34
:POST
enterItem():Store
enterItem():BuyItemHandler
enterItem():Cashier
Overall Organization (façade controller)
Active real world something (role controller)
Artificial handler of all use case operations (use-case controller)
5- The Controller Pattern, cont
35
5- The Controller Pattern, cont
• Many different controller can be used for different use cases.
•A common problem with the controller class is that it has much responsibilities
POST
endSale()enterItem()makePayment()
36
class is that it has much responsibilities (bloated controller), thus it should give some of the other work to other classes.
• Whichever you pick:� never implement system operations in UI classes.� only coordinate other objects’ responsibilities in the controller.
POST if chosen to be the controller class
Summary
• Skillful assignment of responsibilities is extremely important in object-oriented design
• Patterns are named problem/solution pairs that codify good advice and principles related to assignment of good advice and principles related to assignment of responsibilities
• GRASP identifies five patterns or principles:
– Creator, Information Expert, Controller, Low Coupling and High Cohesion
37