0% found this document useful (0 votes)
12 views13 pages

Grasp

The document outlines GRASP (General Responsibility Assignment Software Patterns), which focuses on assigning responsibilities in object-oriented design through nine key patterns. These patterns include Creator, Information Expert, Low Coupling, Controller, High Cohesion, Polymorphism, Pure Fabrication, Indirection, and the Law of Demeter, each addressing specific design challenges. The document emphasizes the importance of low coupling and high cohesion in creating maintainable and reusable software systems.

Uploaded by

rahul7397239918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views13 pages

Grasp

The document outlines GRASP (General Responsibility Assignment Software Patterns), which focuses on assigning responsibilities in object-oriented design through nine key patterns. These patterns include Creator, Information Expert, Low Coupling, Controller, High Cohesion, Polymorphism, Pure Fabrication, Indirection, and the Law of Demeter, each addressing specific design challenges. The document emphasizes the importance of low coupling and high cohesion in creating maintainable and reusable software systems.

Uploaded by

rahul7397239918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

4.

1 GRASP Patterns (General Responsibility Assignment Software Patterns)

Responsibility-Driven Design (RDD)


• A way of thinking about OOD: In terms of Responsibilities, Roles and
Collaborations
• Common responsibility categories:
– Doing:
• Doing something itself:
– Creating an object or doing a calculation
• Initiating action in other objects
• Controlling and coordinating activities in other objects
– Knowing:
• Knowing about private data
• Knowing about related objects
• Knowing about things it can derive or calculate
For example
• Doing - “ a Sale is responsible for creating SalesLineItems”
• Knowing – “ a Sale is responsible for knowing its total”
RDD and Collaboration
• 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.
• For example, the Sale class might define one or more methods to know its total; say, a
method named getTotal.
• To fulfill that responsibility, the Sale may collaborate with other objects, such as sending
agetSubtotal message to each SalesLineltem object asking for its subtotal.
What is Pattern?
– Patterns: A catalog of general principles and idiomatic solutions to guide us in the
creation of software
(Or)
– A pattern: A named and well-known problem/solution pair that Can be applied in
new contexts With advice on how to apply it in novel(new/unusual) situations
Well-known Pattern Families
– GRASP(General Responsibility Assignment Software Patterns ) - 9 Patterns

– GoF(Gang of Four Pattern) – 23 Patterns

• Erich Gamma
• Richard Helm
• Ralph Johnson
• John Vlissides

GRASP Patterns (General Responsibility Assignment Software Patterns) - 9 Patterns


• Creator
– Who creates?
• Information Expert
– Who, in the general case, is responsible?
• Low Coupling
– Support low dependency and increased reuse
• Controller
– Who handles a system event?
• High Cohesion
– How to keep complexity manageable?
• Polymorphism
– Who, when behavior varies by type?
• Pure Fabrication
– Who, when you are Worried, and do not want to violate High Cohesion and Low
Coupling?
• Indirection
– Who, to avoid direct coupling?
• Law of Demeter (Don’t talk to strangers)
– Who, to avoid knowing about the structure of indirect objects?
1. Creator pattern

Name: Creator

Problem: Who creates an instance of A?

Solution: Assign class B the responsibility to create an instance of class A if one of these is:
• B contains or aggregates A (in a collection)
• B records A
• B closely uses A
• B has the initializing data for A

Example:

: Register : Sale

makeLineItem(quantity)
create(quantity) : SalesLineItem

Creator Example:
• Another use: Identify a creator by looking for a class that has the initialization data that will
be passed in during creation.
– Actually an example of the “Expert” pattern
• Initialization data passed in to an “initialization method”
– Often a constructor with parameters
– Or a factory method
• Example:
– A Payment instance, when created needs to be initialized with the Sale total.
– Sale knows Sale total. Good candidate for creating Payment.

2. Information Expert Pattern


• Name: Information Expert or Expert
• Problem: What is a basic principle by which to assign responsibilities to objects?
• Solution (advice): Assign a responsibility to the class that has the information needed to
fulfill it

Example: Information Expert Pattern:

Sale

• What information do we need to determine the grand total of a Sale? time


...
– All the SalesLineItem instances
t = getTotal 1 *: st = getSubtotal lineItems[ i ] :
– Sum of their subtotals
: Sale
SalesLineItem
getTotal()
• A Sale instance contains these
– By “Information Expert”, it is a suitable class for
1.1: p := getPrice() SalesLineItem
computing the grand total
• Next question: What information do we need to know to determine the line item subtotal?
quantity
– Answer: SalesLineItem.quantity and SalesLineItem.price:Product getSubtotal()
• Question: Who knows these? Description

– Answer: SalesLineItem Product


– By “information expert”, SalesLineItem should compute the subtotal Description
• Next issue: Who should return the price of an item? description
– Who knows the price of an item? price
itemID
• ProductDescription
– By “information expert”, SalesLineItem New asks ProductDescription to return
method the price.
getPrice()

3. Low Coupling
• Name: Low Coupling
• Problem: How to reduce the impact of change on software? How to support low
dependency, low change impact, and increased re-use?
• Solution (advice): Assign responsibilities so that (unnecessary) coupling remains low. Use
this principle to evaluate alternatives.
• Why is a class with high (or strong) coupling bad?
• Forced local changes because of changes in related classes
• Harder to understand in isolation
• Harder to re-use
• Because it requires the presence of classes that it depends on
Evaluating the Effect of Coupling
• Coupling: A measure of how strongly one element is connected to, has knowledge of, or
depends on other elements

• The greater the coupling, the greater the dependence between objects

– Coupling is avoided because it goes against OO principles

Why is low coupling good?


• It reduces time, effort and defects involved in modifying software

• The “Expert” pattern supports low coupling

4. Controller pattern

• Name: Controller (see Model-View-Controller architecture)


• Problem: Who should be responsible for UI events?
• Solution: Assign responsibility for receiving or handling a system event in one of two ways:
– Represent the overall system (façade pattern)
– Represent a use case scenario within which the system event occurs (a session
controller)
Controller is doing delegation:
• A delegation pattern

• Use same controller class for all system events of one use case
– Controller maintains information about the state of the use case
– Helps identify out-of-sequence operations
• Example: makePayment before endSale

• Common defect in design of controllers:


Over assignment of responsibility
– Controller may suffer from low cohesion

• Benefits of controller pattern:


– Increased potential for reuse and pluggable interfaces
– Opportunity to reason about the state of the use case

Bloated controller:
• Signs of a bloated controller
– There is a single controller receiving many system events
– Controller itself performs the tasks instead of delegating them
– Controller has many attributes, maintains a lot of info about the system or domain
• Better to distribute these to other objects
• Cures :
– Add more controllers
– Design the controller to delegate the work

Desirable controller

presses button

: Cashier

actionPerformed( actionEvent )

system operation message


UI Layer :SaleJFrame

1: enterItem(itemID, qty)
Undesirable controller

presses button

Cashier

actionPerformed( actionEvent )

It is undesirable for an interface


layer object such as a window to get
UI Layer :SaleJFrame involved in deciding how to handle
domain processes.

Business logic is embedded in the


presentation layer, which is not useful.

1: makeLineItem(itemID, qty)
Domain Layer :Sale

SaleJFrame should not


send this message.

5. High Cohesion

• Name: High Cohesion


• Problem: How to keep objects focused, understandable, and manageable, and as as side
effect, support low coupling
• Solution (advice): Assign responsibilities so that cohesion remains high. Use this to
evaluate alternatives.
Problems with a class with low cohesion:
• Hard to comprehend(understand)
• Hard to reuse
• Hard to maintain
• Constantly affected by change

Danger: Register has potential to do too much work

: Register : Sale

makePayment()
create()
p : Payment

addPayment( p )

Better design: Register delegates, has high cohesion


: Register : Sale

makePayment()
makePayment()
create() : Payment

Modular Design:
• Modularity: The property of a system that has been decomposed into a set of cohesive and
loosely coupled modules
• Exceptions to high cohesion and modularity
– Example: To simplify maintenance by one SQL expert, group all SQL-related
functionality of all classes into one separate class
– Distributed server objects: Because of cost of communication, might make sense to
have few, large server objects
• Example: Instead of three fine-grained operations, setName, setSalary,
setHireDate, have one coarse-grained operation, setData

6. Polymorphism
Problem:
To handle alternatives based on types?
Solution:
When alternate behaviours are selected based on the type of an object, use
polymorphic method call to select the behaviour, rather than using if statement to test the
type.
Polymorphism : Example
Example:desirable: Consider a UML diagram drawing program

• If shapes are responsible for drawing themselves via the draw() method:
– Obviously, an Actor (stick figure) will draw itself differently than a UseCase
(ellipse)
– It might make sense in this case to have the classes themselves handle the drawing
by polymorphically overriding the draw() method
– An advantage is that new entities (e.g. State) can be easily added without changing
the core graphics code
• Polymorphism can lead to highly cohesive objects

Example: undesirable

• Consider the example where some draw() method were implemented similarly to this:
If (entity.type = “UseCase”) then
drawEllipse(…);
Else if (entity.type = “Class”) then
drawRectangle(…);

End if
• This is not highly cohesive, since it combines unrelated behaviours, and it also strongly
couples this object with the shape it draws

7. Pure Fabrication
Problem:
To not violate High Cohesion and Low Coupling?
Solution:
Assign a highly cohesive set of responsibilities to an artificial class that does not represent
anything in the problem domain, in order to support high cohesion, low coupling, and reuse.
Benefits:
● High cohesion is supported because responsibilities are factored into a class that only
focuses on a very specific set of related tasks.
● Reuse potential may be increased because of the presence of fine grained Pure Fabrication
classes.

Example
Suppose, in the point of sale example, that support is needed to save Sale instances in a
relational database. By Expert, there is some justification to assign this responsibility to Sale
class. However.
• The task requires a relatively large number of supporting database-oriented operations and
the Sale class becomes incohesive.
• The sale class has to be coupled to the relational database increasing its coupling.
• Saving objects in a relational database is a very general task for which many classes need
support. Placing these responsibilities in the Sale class suggests there is going to be poor
reuse or lots of duplication in other classes that do the same thing.

• The Sale remains well design, with high cohesion and low coupling

• The PersistentStorageBroker class is itself relatively cohesive

• The PersistentStorageBroker class is a very generic and reusable object

Pure fabrication
● Preserves low coupling and high cohesion of classes

• Improve reusability of classes

8. Indirection
Problem:
To avoid direct coupling?
To de-couple objects so that Low coupling is supported and reuse potential remains high?
Solution:
Assign the responsibility to an intermediate object to mediate between other
components or services, so that they are not directly coupled.

Example: PersistentStorageBroker
The Pure fabrication example of de-coupling the Sale from the relational database services
through the introduction of a PersistentStorageBroker is also an example of assigning
responsibilities to support Indirection. The PersistentStorageBroker acts as an intermediary
between the Sale and database

9. Law of Demeter / Don’t Talk to Strangers


Problem: To avoid knowing about the structure of indirect objects?
Solution: If two classes have no other reason to be directly aware of each other or otherwise
coupled, then the two classes should not directly interact.
● Do not couple two objects who have no obvious need to communicate
This is common sense: do not add coupling where unnecessary
• e.g. Consider a convenience store application
• Customers are people, as are Employees
– Should we model this as inheritance?
• In this application, customers are likely anonymous
– Thus, Employee instances (which likely store names and phone numbers) do not
share any common data or behaviour
• It makes sense that we not model this relationship, despite our initial
reactions

You might also like