6 Grasp

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Introduction to Software Technology

4. GRASP Patterns
Klaus Ostermann

1 Einführung in die Softwaretechnik


GRASP Patterns
} Object Design:
} “After identifying your requirements and creating a domain
model, then add methods to the software classes, and define
the messaging between the objects to fulfill the
requirements.”
} But how?
} What method belongs where?
} How should the objects interact?
} This is a critical, important, and non-trivial task

2 Einführung in die Softwaretechnik


GRASP Patterns
} The GRASP patterns are a learning aid to
} help one understand essential object design
} apply design reasoning in a methodical, rational, explainable
way.
} This approach to understanding and using design
principles is based on patterns of assigning
responsibilities

3 Einführung in die Softwaretechnik


GRASP - Responsibilities
} Responsibilities are related to the obligations of an object in
terms of its behavior.
} Two types of responsibilities:
} knowing
} doing
} 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

4 Einführung in die Softwaretechnik


Design patterns in architecture
} A pattern is a recurring solution to a standard problem,
in a context.
} Christopher Alexander, professor of architecture…
} Why is what a prof of architecture
says relevant to software?
} “A pattern describes a problem
which occurs over and over again
in our environment, and then
describes the core of the solution
to that problem, in such a way that
you can use this solution a million
times over, without ever doing it
the same way twice.”
Patterns in engineering
} How do other engineers find and use patterns?
} Mature engineering disciplines have handbooks
describing successful solutions to known problems
} Automobile designers don't design cars from scratch
using the laws of physics
} Instead, they reuse standard designs with successful
track records, learning from experience
} Should software engineers make use of patterns? Why?
} Developing software from scratch is also expensive
} Patterns are a form of reuse of software design
Definitions and names
} Alexander: “A pattern is a recurring solution
to a standard problem, in a context.”
} Larman: “In OO design, a pattern is a named
description of a problem and solution that can be
applied in new contexts; ideally,
a pattern advises us on how to apply the solution
in varying circumstances and considers
the forces and trade-offs.”
Basic Pattern Principles
} Patterns are never invented; they are found
} they codify existing tried-and-true knowledge, idioms, and
principles
} the more honed and widely used, the better
} Patterns give a name to an idea!

Fred: "Where do you think we should place the


responsibility for creating a SalesLineltem? I think a Factory."
Wilma: "By Creator, I think Sale will be suitable."
Fred: "Oh, right - I agree."

8 Einführung in die Softwaretechnik


GRASP
} Name chosen to suggest the importance of grasping
fundamental principles to successfully design object-
oriented software
} Acronym for General Responsibility
Assignment Software Patterns
} (technically “GRASP Patterns” is hence
redundant but it sounds better)
} Describe fundamental principles of
object design and responsibility
} Expressed as patterns
Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
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
} Start assigning responsibilities by clearly stating
responsibilities!
} For instance, in a POS application a statement might be:
“Who should be responsible for knowing the grand total
of a sale"?

12 Einführung in die Softwaretechnik


Information Expert
} What information is needed to determine the grand
total?

} Sale is the information expert for this responsibility.

13 Einführung in die Softwaretechnik


Information Expert
} What information is needed to determine the line item
subtotal?

14 Einführung in die Softwaretechnik


Information Expert
} To fulfill the responsibility of knowing and answering its
subtotal, a SalesLineltem needs to know the product
price.
} The ProductSpecification is an information expert on
answering its price; therefore, a message must be sent to
it asking for its price.

15 Einführung in die Softwaretechnik


Information Expert
} To fulfill the responsibility of knowing and answering the
sale's total, three responsibilities were assigned to three
design classes of objects

16 Einführung in die Softwaretechnik


Information Expert: Final Design

17 Einführung in die Softwaretechnik


Information Expert: Discussion
} Expert usually leads to designs where a software object
does those operations that are normally done to the
inanimate real-world thing it represents
} a sale does not tell you its total; it is an inanimate thing
} In OO design, all software objects are "alive" or
"animated," and they can take on responsibilities and do
things.
} They do things related to the information they know.

18 Einführung in die Softwaretechnik


Information Expert: Discussion
} Contraindication: Conflict with separation of concerns
} Example: Who is responsible for saving a sale in the database?
} Adding this responsibility to Sale would distribute database
logic over many classes à low cohesion
} Contraindication: Conflict with late binding
} Late binding is available only for the receiver object
} But maybe the variability of late binding is needed in some
method argument instead
} Example: Support for multiple serialization strategies

19 Einführung in die Softwaretechnik


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Creator
Problem:
Assign responsibility for creating a new instance of some
class?
Solution:
Determine which class should create instances of a class
based on the relationship between potential creator
classes and the class to be instantiated.

21
Creator
} who has responsibility to create an object?
} By creator, assign class B responsibility of creating instance of
class A if
} B aggregates A objects
} B contains A objects
} B records instances of A objects
} B closely uses A objects
} B has the initializing data for creating A objects
} where there is a choice, prefer
} B aggregates or contains A objects

22
Creator : Example
Who is responsible for creating SalesLineItem objects?
Look for a class that aggregates or contains SalesLineItem objects.

Sale

date
time

Contain
s
1.. *
Product
Sales Specification
LineItem * Described-
by description
quantity price
UPC

23
Creator : Example
Creator pattern suggests Sale.

Collaboration diagram is

24
Creator
} Promotes low coupling by making instances of a class
responsible for creating objects they need to reference
} By creating the objects themselves, they avoid being
dependent on another class to create the object for them

25
Creator: Discussion
} Contraindications:
} creation may require significant complexity, such as
} using recycled instances for performance reasons
} conditionally creating an instance from one of a family of similar
classes based upon some external property value
} Sometimes desired to outsource object wiring (“dependency
injection”)
} Related patterns:
} Abstract Factory, Singleton, Dependency Injection

26 Einführung in die Softwaretechnik


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Low Coupling
Problem:
How to support low dependency, low change impact,
and increased reuse.

Solution:
Assign a responsibility so that coupling remains low.

28
Why High Coupling is undesirable
} 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 dependent
on too many other elements (classes, subsystems, …)
} "too many" is context-dependent
} A class with high (or strong) coupling relies on many
other classes.
} Changes in related classes force local changes.
} Such classes are harder to understand in isolation.
} They are harder to reuse because its use requires the
additional presence of the classes on which it is dependent.

29 Einführung in die Softwaretechnik


Low Coupling
How can we make classes independent of other classes?

changes are localised


easier to understand
easier to reuse

Who has responsibility to create a payment and associate it to a


sale?

30
Low Coupling
Two possibilities:

1. Register

2. Sale

Low coupling suggests Sale because Sale has to be


coupled to Payment anyway (Sale knows its total).
31
Common Forms of Coupling in OO Languages
} TypeX has an attribute (data member or instance variable)
that refers to a TypeY instance, or TypeY itself.
} TypeX has a method which references an instance of TypeY, or
TypeY itself, by any means.
} Typically include a parameter or local variable of type TypeY, or the
object returned from a message being an instance of TypeY.
} TypeX is a direct or indirect subclass of TypeY.
} TypeY is an interface, and TypeX implements that interface.

32
Low Coupling: Discussion
} Low Coupling is a principle to keep in mind during all
design decisions
} It is an underlying goal to continually consider.
} It is an evaluative principle that a designer applies while
evaluating all design decisions.
} Low Coupling supports the design of classes that are
more independent
} reduces the impact of change.
} Can't be considered in isolation from other patterns such
as Expert and High Cohesion
} Needs to be included as one of several design principles
that influence a choice in assigning a responsibility.

33 Einführung in die Softwaretechnik


Low Coupling: Discussion
} Subclassing produces a particularly problematic form of
high coupling
} Dependence on implementation details of superclass
} “Fragile Base Class Problem” [see SE Design Lecture]
} Extremely low coupling may lead to a poor design
} Few incohesive, bloated classes do all the work; all other
classes are just data containers
} Contraindications: High coupling to very stable elements
is usually not problematic

34 Einführung in die Softwaretechnik


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
High Cohesion
Problem:
How to keep complexity manageable.
Solution:
Assign responsibilities so that cohesion remains high.

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

36
High cohesion
} Classes are easier to maintain
} Easier to understand
} Often support low coupling
} Supports reuse because of fine grained responsibility

37
High Cohesion
Who has responsibility to create a payment?

1.Register

looks OK if makePayement considered in isolation, but


adding more system operations, Register would take on
more and more responsibilities and become less cohesive.

38
High Cohesion
Giving responsibility to Sale supports higher cohesion in Register, as well as
low coupling.

39
High Cohesion: Discussion
} Scenarios:
} Very Low Cohesion: A Class is solely responsible for many things in very
different functional areas
} Low Cohesion: A class has sole responsibility for a complex task in one
functional area.
} High Cohesion. A class has moderate responsibilities in one functional area
and collaborates with classes to fulfil tasks.
} Advantages:
} Classes are easier to maintain
} Easier to understand
} Often support low coupling
} Supports reuse because of fine grained responsibility
} Rule of thumb: a class with high cohesion has a relatively small
number of methods, with highly related functionality, and does not
do too much work.

40
Problem: High Cohesion and Viewpoints

41 Einführung in die Softwaretechnik [Harrison&Ossher ‘93]


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Controller
Problem:
Who should be responsible for handling an input system
event?
Solution:
Assign the responsibility for receiving or handling a
system event message to a class representing the overall
system, device, or subsystem (facade controller) or a use
case scenario within which the system event occurs (use
case controller)

43
Controller: Example

44 Einführung in die Softwaretechnik


Controller: Example
} By the Controller pattern, here are some choices:
} Register, POSSystem: represents the overall "system,"
device, or subsystem
} ProcessSaleSession, ProcessSaleHandler: represents a
receiver or handler of all system events of a use case
scenario

45 Einführung in die Softwaretechnik


Controller: Discussion
} Normally, a controller should delegate to other objects
the work that needs to be done; it coordinates or
controls the activity. It does not do much work itself.
} Facade controllers are suitable when there are not "too
many" system events
} A use case controller is an alternative to consider when
placing the responsibilities in a facade controller leads to
designs with low cohesion or high coupling
} typically when the facade controller is becoming "bloated"
with excessive responsibilities.

46 Einführung in die Softwaretechnik


Controller: Discussion
} Benefits
} Increased potential for reuse, and pluggable interfaces
} No application logic in the GUI
} Dedicated place to place state that belongs to some use case
} E.g. operations must be performed in a specific order
} Avoid bloated controllers!
} E.g. single controller for the whole system, low cohesion, lots
of state in controller
} Split into use case controllers, if applicable
} Interface layer does not handle system events

47 Einführung in die Softwaretechnik


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Polymorphism
Problem:
How to handle alternatives based on types?
How to create pluggable software components?
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/case statement to test
the type.

49
Polymorphism: Example

50 Einführung in die Softwaretechnik


Polymorphism: Discussion
} Polymorphism is a fundamental principle in designing
how a system is organized to handle similar variations.
} Properties:
} Easier and more reliable than using explicit selection logic
} Easier to add additional behaviors later on
} Increases the number classes in a design
} May make the code less easy to follow
} Using the principle excessively for “future-proofing”
against yet unknown potential future variations is a bad
idea
} Agile methods recommend to do no significant “upfront
design” and add the variation point only when the need arises

51
Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Pure Fabrication
Problem:
Adding some responsibilities to domain objects
would violate high cohesion/low coupling/reuse
Solution:
Assign a highly cohesive set of responsibilities to an
artificial or convenience class that does not represent
a problem domain concept—something made up, to
support high cohesion, low coupling, and reuse.

53
Pure Fabrication: Example
} In the point of sale example 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.

54
Pure Fabrication : Example
} Solution: create a new class that is solely responsible for
saving objects in a persistent storage medium
} This class is a Pure Fabrication

} The Sale remains well-designed, with high cohesion and low


coupling
} The PersistentStorageBroker class is itself relatively cohesive
} The PersistentStorageBroker class is a very generic and reusable
object
55
Pure Fabrication: Discussion
} The design of objects can be broadly divided into two
groups:
} Those chosen by representational decomposition (e.g. Sale)
} Those chosen by behavioral decomposition (e.g. an algorithm
object such as TOCGenerator or PersistentStorage)
} Both choices are valid designs, although the second one
corresponds less well to the modeling perspective on
objects
} If overused, it can lead to a non-idiomatic design, namely
a separation of the code into data and behavior as in
procedural programming
} Coupling of data and behavior is central to OO design

56
Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Indirection
Problem:
Where to assign a responsibility, to avoid direct coupling
between two (or more) things?
How to de-couple objects so that low coupling is supported
and reuse potential remains higher?

Solution:
Assign the responsibility to an intermediate object to mediate
between other components or services, so that they are not
directly coupled.

"Most problems in computer science can be solved


by another level of indirection"

58
Indirection: Example

By adding a level of indirection and adding polymorphism, the adapter objects


protect the inner design against variations in the external interfaces

59 Einführung in die Softwaretechnik


Nine GRASP patterns:
} Information Expert
} Creator
} Low Coupling
} Controller
} High Cohesion
} Polymorphism
} Indirection
} Pure Fabrication
} Protected Variations
Protected Variation
Problem:
How to design objects, subsystems, and systems so that the
variations or instability in these elements does not have an
undesirable impact on other elements?

Solution:
Identify points of predicted variation or instability; assign
responsibilities to create a stable interface around them.

Note: This is basically just another formulation of the


information hiding principle.

61 Einführung in die Softwaretechnik


Protected Variation: Examples
} Data encapsulation, interfaces, polymorphism,
indirection, and standards are motivated by PV.
} Virtual machines are complex examples of indirection to
achieve PV
} Service lookup: Clients are protected from variations in
the location of services, using the stable interface of the
lookup service.
} Uniform Access Principle
} Law of Demeter
} …

62 Einführung in die Softwaretechnik


Literature
} Craig Larman, Applying UML and Patterns, Prentice Hall,
2004
} Chapter 16+17+22 introduce GRASP

63 Einführung in die Softwaretechnik

You might also like