Upload
rajafahim
View
215
Download
0
Embed Size (px)
Citation preview
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
1/67
1
Patters
Designing Objects with Responsibilities
GRASP Patterns
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
2/67
2
: System
enterItem(id, quantity)
endSale()
makePayment(amount)
Process Sale
1. Customerarrives ...2. Cashiermakes newsale.3. Cashierenters itemidentifier.4....
Use Cases System Sequence Diagrams
Operation: enterItem
Post-conditions:- A SalesLineItem instancesli was created-. . .
Operation: makeNewSale
Post-conditions:- . . .
Contracts
makeNewSale()
: Cashier
Sale
date. . .
SalesLineItem
quantity
1..*1 . . .
. . .
domain objects
systemevents
systemoperations
the domain objects, attributes, andassociations that undergo state changes
Domain Model
Use-Case Model
some ideas and inspiration for the post-conditions derive from the use cases
Design Model
: Register
enterItem(itemID, quantity)
: ProductCatalog
spec := getSpecification( itemID )
addLineItem( spec, quantity )
: Sale
. . .
in addition to the usecases, requirements thatmust be satisfied by thedesign of the software
use-caserealization
conceptualclasses in
thedomaininspire thenames ofsomesoftwareclasses inthe design
makeNewSale()create()
endSale(). . .. . .
Sample UP Artifact Relationships for Use-Case Realization
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
3/67
3
Methods Responsibilities
Deciding what methods belong where, and how the objects should
interact, is most important
The GRASP patterns are a learning aid to help one in understanding
essential object design
GRASP stands for General Responsibility Assignment SoftwarePatterns
UML defines Responsibility as
a contract or obligation of a class
Responsibilities are related to the obligations of an object in terms
of its behavior
Responsibilities are of two types
Doing
Knowing
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
4/67
4
Responsibilities and Methods
Doing responsibilities of an object include
Doing something itself such as creating an object or
doing a calculation
Initiating action in other objects
Controlling and coordinating activities in other objects
Knowing responsibilities of an object include
knowing about private encapsulated data
Knowing about related objects Knowing about things it can derive or calculate
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
5/67
5
Responsibilities and Methods
Responsibilities are assigned during object design
A Sale is responsible for creating SalesLineItem instances
(doing)
A Sale is responsible for knowing its total (knowing) A responsibility is not the same thing as a method, but
methods are implemented to fulfill responsibilities
Responsibilities are implemented using methods that either
act alone or collaborate with other methods and objects
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
6/67
6
Example
The class Sale might define one or more methods to
know its total (say a getTotalmethod). To fulfill that
responsibility, the Sale may collaborate with other
objects e.g. sending a getSubTotalmessage to each
SalesLineItem object
Responsibilities and Methods
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
7/67
7
Responsibilities and Interaction Diagrams
Creation of interaction diagrams needs fundamentalprinciples (called Patterns) for assigning responsibilities toobjects
: Sale
makePayment(cashTendered)
: Paymentcreate(cashTendered)
implies Sale objects have a
responsibility to create Payments
Interaction diagrams show choices in assigning
responsibilities to objects
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
8/67
8
Patterns
A Pattern is a named description of a problem and solution
that can be applied to assign responsibilities
Patterns provide guidance for how responsibilities should be
assigned to objects
Pattern Name: Information Expert
Solution: Assign a responsibility to the
class that has the information
needed to fulfill it
Problem it Solves: What is a basic principle by
which to assign responsibilities to
objects?
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
9/67
9
GRASP Patterns
First five GRASP patterns
Information Expert
Creator
High Cohesion Low coupling
Controller
There are other patterns as well, but these address very
basic, common questions and fundamental design issues
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
10/67
10
Information Expert
Problem
What is a general principle of assigning responsibilities
to objects?
Solution
Assign a responsibility to the information Expert the
class that has the information necessary to fulfill the
responsibility
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
11/67
11
Information Expert
Problem Explanation
A design Model may define hundreds of software classes and an
application may require hundreds of responsibilities to be
fulfilled.
When the interactions between objects are defined, we make
choices about the assignment of responsibilities to software
classes.
If responsibility assignment is done well
Systems tend to be easier to understand, maintain and
extend and there is more opportunity to reuse components
in future applications.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
12/67
12
Information Expert
Example
In the NextGenPOS application, some class needs to
know the grand total of a sale
Start assigning responsibilities by clearly stating theresponsibility
Who should be responsible for knowing the grand
total of a Sale?
By Information Expert we should look for that class
that has the information needed to determine the total.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
13/67
13
Information Expert
Example
Sale
date
time
Sales
LineItem
quantity
ProductSpecification
descriptionpriceitemID
Described-by*
Contains
1..*
1
1
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
14/67
14
Information Expert
Example
What Information is needed to determine the grand total?
It is necessary to know about all the SalesLineItem
instances of a sale and the sum of their subtotal
Sale class contains this information, therefore suitable
for this responsibility i.e. getTotal
Itis an Information Expert for this work
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
15/67
15
Information Expert
A partial solution
Sale
datetime
getTotal()
:Salet := getTotal()
New method
Partial interaction and class diagram
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
16/67
16
Information Expert
Example
What information is needed to determine theSlaesLineItem subtotal?
SalesLineItem.quantityand SalesLineItem.price
Now
SalesLineItem knows its quantity and it is associated
with ProductSpecification By Information Expert, SalesLineItem should determine
subtotal
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
17/67
17
Information Expert
Example
In terms of Interaction Diagram it means that Sale needs to sendgetSubtotal message to each of the SalesLineIteminstance
Sale
datetime
getTotal()
SalesLineItem
quantity
getSubtotal()New method
1 *: st := getSubtotal(): Sale
t := getTotal() lineItems [i]:SalesLineItem
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
18/67
18
Information Expert
Example cont
For knowing and answering its subtotal a SalesLineItem
needs to know the product price
ProductSpecification is expert for price of a
salesLineItem
A message must be sent to it asking for price
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
19/67
19
Information Expert
Example
Conclusion
To fulfill the responsibility ofknowing and answeringthe sale's total, threeresponsibilities wereassigned to three design
classes of objects
The principle by which each responsibility was assigned was InformationExpert- placing it with the object that has the information needed tofulfill it
Sale
datetime
getTotal()
SalesLineItem
quantity
getSubtotal()
ProductSpecification
descriptionpriceitemID
getPrice()New method
:ProductSpecification
1.1: p := getPrice()
1 *: st := getSubtotal(): Salet := getTotal()
lineItems [i]:
SalesLineItem
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
20/67
20
Information Expert
Benefits Information Encapsulation is maintained
As objects use their own information to fulfill
tasks
Low coupling is promoted More robust and maintainable systems
High cohesion is promoted
Behavior is distributed across classes that have
the information
Related Patterns (to be discussed)
Low Coupling
High Cohesion
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
21/67
21
Creator
Problem
Who should be responsible for creating a new
instance of some class?
Creation of objects is most common activity
It is useful to have a general principle for assignment of
creation responsibilities
Assigned well, the design can support low coupling,
increased clarity, encapsulation and reusability
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
22/67
22
Creator
Solution
Assign class B the responsibility to create an instance of
class A if one or more of the following conditions is true
B contains orcompositelyaggregates A objects.
B records instances ofA objects.
B closely uses A objects.
B has initializing data that will be passed to A when it is
created
B is creator of A objects.
If more than one options, prefer a class B which compositely
aggregates or contains class A
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
23/67
23
Creator
Sometimes a creator is found by looking for the class that has the
initializing data that will be passed in during instance creation
Initializing data is passed in during creation via some kind of
initialization method, such as a Java or C++ constructor that has
parameters
Example: a Payment instance needs to be initialized, when
created with the Sale total.
Since Sale knows the total, Sale is a candidate creator of the
payment
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
24/67
24
Creator
Example
In the POS application, who should be
responsible for creating a SalesLineItem
instance?
By Creator,
We should look for a class that aggregates, contains
and so on, SalesLineItem instances
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
25/67
25
Creator
Example
Consider partial domain Model
Sale
datetime
SalesLineItem
quantity
Product
Specification
descriptionpriceitemID
Described-by*
Contains
1..*
1
1
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
26/67
26
Creator
Example
Since Sale contains many SalesLineItem Objects
Creator pattern suggests that Sale is a good
candidate to have the responsibility of creating
SalesLineItem instances.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
27/67
27
Creator
Example
This assignment of responsibilities requires that a makeLineItem
method be defined in Sale
: Register : Sale
makeLineItem(quantity)lineItems:
Listcreate(quantity)
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
28/67
28
Creator
Benefits
Low Coupling is supported
Which implies lower maintenance dependencies, and
higher opportunities of reuse
Coupling is not increased because the created class is
already visible to creator class due to existing association
Related Patterns
Low coupling
Factory
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
29/67
29
Coupling
Coupling is a measure of how strongly one element is
connected to, has knowledge of, or relies on other
elements.
An element with low or weak coupling is not dependant
on too many other elements
Elements include classes , subsystems, systems etc.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
30/67
30
Coupling
A class with high or strong coupling relies on many
other classes
Some classes may be undesirable; and suffer from
following problems Changes in related classes force local changes
Harder to understand in isolation
Harder to reuse because its use requires the additional
presence of the classes on which it is dependant.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
31/67
31
Low coupling
Problem
How to support low dependency, low changeimpact and increased reuse?
Solution
Assign responsibilities so that coupling remainslow
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
32/67
32
Low coupling
Example Consider the following partial diagram
Payment Register Sale
Assume we have a need to create a payment instance
and associate with the sale
What class should be responsible for this?
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
33/67
33
Low coupling
Example
Register records a payment in real world domain
Creator pattern suggests Register for creating
payment
The register instance could then send an
addPayment message to Sale , passing along the
new Payment as parameter.
Interaction diagram reflecting this would be
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
34/67
34
Low coupling
: Register p : Payment
:Sale
makePayment() 1: create()
2: addPayment(p)
Notethat Payment instance is explicitly named p so that
in message2 it can be referenced as parameter
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
35/67
35
Low coupling
An alternative solution
: Register :Sale
:Payment
makePayment() 1: makePayment()
1.1. create()
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
36/67
36
Low coupling
Example
Which design based on assignment of responsibilities
supports low coupling?
Sales must be coupled with payment
Diagram1, in which the Register creates the payment,
adds coupling ofpayment
In Diagram2 Sale does the creation of payment and it
does not increase coupling
From the point of view of Coupling Design2 is preferable
An example, where two patterns suggests different
solutions
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
37/67
37
Low Coupling
Benefits
Not affected by changes in other components
Simple to understand in isolation
Convenient to reuse
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
38/67
38
Low Coupling
In Practice the level of coupling alone cant be
Considered in isolation from other principles
Such as Expert and high cohesion. Nevertheless
It is one factor to consider in improving a design
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
39/67
39
Cohesion
Cohesion is a measure of how strongly related and focused
the responsibilities of an element are.
An element with highly related responsibilities and which
does not do a tremendous amount of work, has high
cohesion.
A class with low cohesion does many unrelated things, or
does too much work.
Such classes are undesirable; they suffer from many
problems
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
40/67
40
Cohesion
Low Cohesion classes suffer from problems like;
Hard to comprehend (understand)
Hard to reuse
Hard to maintain
Delicate; constantly affected by change
Low cohesion classes often have taken on responsibilities
that should have been delegated to other classes
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
41/67
41
High Cohesion
Problem
How to keep complexity manageable?
Solution
Assign a responsibility so that cohesion remains high
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
42/67
42
High Cohesion
Example (same example problem used in Low Coupling pattern can
be analyzed for High Cohesion)
We have a need to create a Paymentinstance and associate it with
Sale.
Which class should be responsible for it?
As discussed earlier, in real world domain Register records
Payment
Creator Pattern suggests Registeras a candidate class for creating
a Paymentinstance
Registerinstance could then send an addPaymentmessage to the
Sale passing new Paymentinstance as a parameter
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
43/67
43
High Cohesion
Example
RegisterCreates Payment
: Register p : Payment
:Sale
makePayment() 1: create()
2: addPayment(p)
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
44/67
44
High Cohesion
This single system event does not make Registerclass incohesive
But there exists many related system events (e.g. fifty systemoperations/events)
IfRegisteris assigned responsibility for all these system operations; it
may become incohesive object
Example RegisterCreates Payment
Second design ( next example ) supports high cohesion and low coupling
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
45/67
45
High Cohesion
: Register : Sale
makePayment()
: Paymentcreate()
makePayment()
Example Sale Creates Payment
Since the second design supports both high cohesion and low coupling,
it is preferable
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
46/67
46
High Cohesion
In Practice, the level of cohesion alone can
not be considered in isolation from other
responsibilities and other principles such
as Information Expert and Low Coupling
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
47/67
47
High Cohesion
Functional Cohesion
When the elements of a component (a class)all work together to
provide some well-bounded behavior[Grady Booch 94]
Scenarios that illustrate varying degrees of functional cohesion
Very Low Cohesion
Low Cohesion
High Cohesion Moderate Cohesion
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
48/67
48
High Cohesion
Very Low Cohesion
A class is solely responsible for many things in different
functional areas
Example
Assume A class RDB-RPC-Interface That is completely responsible for interacting with Relational
Databases and for Remote Procedure Calls.
These two are vastly different areas and each requires lots of
supporting code
Therefore, the responsibilities should be split into a family of classesrelated to RDB access and a family related to RPC support
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
49/67
49
High Cohesion
Low Cohesion
A class has sole responsibility for a complex task in one functional
area
Example
Assume A class RDBInterface
That is completely responsible for interacting with Relational Database
The methods of the class are all related, but there are lots of them,
and there is a tremendous amount of supporting code;
There may be hundreds of methods
The class should be split into a family of light-weight classes sharing
the work to provide RDB access
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
50/67
50
High Cohesion
High Cohesion
A class has moderate (reasonable) responsibilities
in one functional area and collaborates with other
classes to fulfill tasks
Example
Assume A class RDBInterface having partial responsibility for
interacting with RDB
It interacts with a dozen (may be) other classes related to RDB
access in order to retrieve and save objects
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
51/67
51
High Cohesion
Moderate Cohesion
A class has lightweight and sole responsibilities in a few
different areas that are logically related to the class
concept, but not to each other.
Example
Assume A class Companythat is completely responsible for
knowing its employees information and
Knowing its financial information
These two areas are not strongly related to each other although
these two are logically related to the concept ofCompany
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
52/67
52
High Cohesion
Benefits
Clarity and ease of comprehension (understanding) of the
design
Maintenance and enhancements are simplified
Low coupling is often supported
The fine grain of highly related functionality supports increased
reuse because a cohesive class can be used for a very specific
purpose
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
53/67
53
Controller Pattern
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
54/67
54
Controller
It is related with handling an input system event? An input system event is an event generated by an external actor
They are associated with system operations
Operations of the system in response to system events, just asmessages and methods are related
When A Cashier (in POS) presses endSale button, he isgenerating a system event indicatingthe sale has ended
When a person presses the SpellCheck button (in a WordProcessor), and generating the event, indicatingperform a spell
check
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
55/67
55
Controller
What is Controller?
A Controller is a non user interface object responsible forreceiving or handling a system event
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
56/67
56
Controller Problem
Who should be responsible for handling an input system event?
Solution
Assign the responsibility for receiving or handling a system eventmessage to a class representing one of the following choices
Class that represents the overall system, device or subsystem
Class that represents a use case scenario within which thesystem event occurs, often named as;
Handler
Coordinator
Session
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
57/67
57
Controller
Example In NextGenPOS there are different system operations
System
endSale()enterItem()makeNewSale()makePayment()
. . .
Who should be responsible for system events like enterItemand endSale
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
58/67
58
Controller
Which class of object should be responsible for
receiving thissystem event message?
It is sometimes called the controller or coordinator. It does not normally do the work, but delegates it to other objects.
The controller is a kind of "facade" onto the domain layer
from the interface layer.
actionPerformed( actionEvent )
: ???
: Cashier
:SaleJFrame
presses button
enterItem(itemID, qty)
InterfaceLayer
DomainLayer
System event message
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
59/67
59
Controller
Example By Controller choices for controller are
The class that represents overall system, device orsubsystem
The class that represents a receiver or handler of allsystem events of a use case scenario
--- Register, POS System
--- ProcessSaleHandler
--- ProcessSaleSession
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
60/67
60
Controller
In terms of Interaction Diagrams, it means that one of theexamples in following figure may be useful
:RegisterenterItem(id, quantity)
:ProcessSaleHandleenterItem(id, quantity)
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
61/67
61
Controller
Normally, a controller should delegate to other objects thework that needs to be done; it coordinates or controls theactivity. It does not do much work itself.
Faade controller
Represents the overall system, device or subsystem.
The idea is to choose some class name that Suggests a cover or faade (front wall) over the other layers of the
application and
That provides the main point of service calls from the UI (UserInterface) layer down to other layers.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
62/67
62
Controller
Faade controllers are suitable when there are not toomany system events
Use case Controller
Choose a use case controller when Faade controller isbecomingbloatedwith excessive responsibilities
Different controller for each use case e.g.ProcessSaleHandler, HandleReturnsHandler
It is not a domain object, rather an artificial construct tosupport the system
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
63/67
63
Controller
Register
...
endSale()enterItem()makeNewSale()makePayment()
makeNewReturn()enterReturnItem(). . .
System
endSale()enterItem()makeNewSale()makePayment()
makeNewReturn()enterReturnItem(). . .
system operationsdiscovered during systembehavior analysis
allocation of systemoperations during design,using one facade controller
ProcessSaleHandler
...
endSale()enterItem()makeNewSale()makePayment()
System
endSale()enterItem()makeNewSale()makePayment()
enterReturnItem()makeNewReturn(). . .
allocation of systemoperations during design,using several use case
controllers
HandleReturnsHandler
...
enterReturnItem()makeNewReturn(). . .
Allocation of SystemOperations
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
64/67
64
Controller
Benefits
Increased potential for reuse and pluggable interfaces
It ensures that Application logic is not handled in interfacelayer
Application logic is not bound to interface layer
Reasoning about the state of use case To ensure that system operations occur in legal sequence
E.g. makePaymentoperation cannot occur before endSale operation
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
65/67
65
Controller
Issues Poorly designed a controller class will have low cohesion --
unfocused and handling too many areas of responsibility; calledBloated Controller. Signs are
A single controller class, receiving all system events
Controller class itself performs many tasks withoutdelegating work. This usually involves violation ofInformation Expert and High Cohesion
A controller has many attributes and maintains significantinformation about domain, which should have beendistributed to other objects, or duplicates information found
elsewhere.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
66/67
66
Controller
Solutions to Bloated Controller Add more controllers instead of faade, use use-case
controllers
For example, in an airline reservation system; there may bemany controllers (MakeReservationHandler,
ManageScheduleHadler, ManageFaresHandler) rather than justone facade
Design the controller so that it primarily delegates thefulfillment of each system operation responsibility on to otherobjects.
8/2/2019 Lecture 9 GRASP Designing Objects With Responsibilities Information Expert
67/67
Controller
Related Patterns Command
Faade
Layers
Separating domain logic from presentation layer Pure Fabrication
Use case controller