Вы находитесь на странице: 1из 49

GRASP: Designing Objects

with Responsibilities

Nosheen Anwar
What is GRASP
• Acronym for General Responsibility Assignment Software Patterns.
• Guidelines for assigning responsibility to classes and objects
• GRASP is a design pattern in object-oriented software development.
• Describe fundamental principles of object design and responsibility .
• A learning aid for OO design with Responsibilities
• Assign responsibilities to objects while coding or drawing interaction diagrams.
• GRASP with object-oriented programming classifies problems and their solutions
together as patterns.
• these problems and solutions well defined, they can be applied in other similar
instances.
• GRASP assigns seven types of roles to classes and objects in order to make for
clear delineation of responsibilities.

2
GRASP

• GRASP is occasionally coupled with other design patterns such as SOLID. This combination
makes for the convincing moniker of SOLID GRASP.
• Design patterns such as these help keep code simpler, more organized, more comprehensible,
analyzable and reusable.
• The GRASP design patterns are a set of design patterns that came after the original Gang of
Four book that many of you might be familiar with.
• These patterns, as the name suggests, aim primarily to answer the question: “Who does what?”
• It help guide object-oriented design by clearly outlining who does what: which object or class is
responsible for what action or role.
• GRASP also helps us define how classes work with one another.
• The key point of GRASP is to have efficient, clean, understandable code.

3
Responsibilities
• Responsibility is a “Contract or obligation of a classifier”
• Responsibilities can be include the behavior, data storage object creation and more….
• Responsibilities of an Object include two types : Knowing and 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 (know thyself, presume not God to scan)
• Knowing about related objects
• Knowing about things it can derive or calculate
• Responsibilities are an abstraction – methods fulfill responsibilities
• Responsibilities are implemented by means of methods that either act alone or collaborate
with other methods and objects. 2
4
Responsibility-Driven Design (RDD)
• A way of thinking about OOD:
• In terms of
• Responsibilities
• Roles
• Collaborations
• Bigger responsibilities may take several classes
• Guideline:
• Domain model helps with “knowing”
• Interaction diagrams help with “doing”

5
Design and dress patterns
• Jim Coplein, a software engineer:
“I like to relate this definition to dress patterns …
I could tell you how to make a dress by specifying the route of a scissors through a
piece of cloth in terms of angles and lengths of cut. Or, I could give you a pattern.
Reading the specification, you would have no idea what was being built or if you had
built the right thing when you were finished. The pattern foreshadows the product: it is
the rule for making the thing, but it is also,
in many respects, the thing itself.”

6
• The “patterns” provide a representation of nine basic principles that form a
foundation for designing object oriented systems.
• Creator
• Controller
• Pure Fabrication
• Information Expert
• High Cohesion
• Indirection
• Low Coupling
• Polymorphism
• Protected Variations

7
What is a Design Pattern?

 A (Problem, Solution) pair.

• A technique to repeat designer success.

• Borrowed from Civil and Electrical Engineering domains.

8
Design Pattern: Definitions

• A pattern is a recurring solution to a standard problem, in a context.


• Christopher Alexander, a professor of architecture…
“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.”

9
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?
“Be sure that you make everything according to the pattern

• Developing software from scratch is also expensive


• Patterns support reuse of software architecture and design

10
Design Patterns
• Patterns: A repertoire of
• general principles
• idiomatic solutions
to guide us in the creation of software
• 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 situations
• With a discussion of its trade-offs, implementations, variations, …
• Names facilitate communication about software solutions
• Some patterns may seem obvious: That’s a good thing!

11
Design Patterns

• Design patterns represent the best practices used by experienced object-oriented


software developers.
• Design patterns are solutions to general problems that software developers
faced during software development.
• These solutions were obtained by trial and error by numerous software
developers over quite a substantial period of time.

12
How Patterns are used?
Designer

• Design Problem.
• Solution.
Programmer

• Implementation details.

Reduce gap

Design Implementation

13
Benefits of Design Patterns

• Design patterns enable large-scale reuse of software architectures and also


help document systems
• Patterns explicitly capture expert knowledge and design tradeoffs and
make it more widely available
• Patterns help improve developer communication
• Pattern names form a common vocabulary

14
Elements of Design Patterns

• Design patterns have 4 essential elements:


• Pattern name: increases vocabulary of designers
• Problem: intent, context, when to apply
• Solution: UML-like structure, abstract code
• Consequences: results and tradeoffs

15
Name of Design Pattern

 Describe a design problems and its solutions in a word or two


 Used to talk about design pattern with our colleagues
 Used in the documentation
 Increase our design vocabulary
 Have to be coherent

16
Problem

• Describes when to apply the patterns


• Explains the problem and its context
• Sometimes include a list of conditions that must be met before
it makes sense to apply the pattern
• Have to occurs over and over again in our environment

17
Solution

• Describes the elements that make up the design, their


relationships, responsibilities and collaborations

• Does not describe a concrete design or implementation

• Has to be well proven in some projects

18
Consequences

• Results and trade-offs of applying the pattern

• Helpful for describing design decisions, for evaluating design


alternatives

• Benefits of applying a pattern

• Impacts on a system’s flexibility, extensibility or portability

19
GRASP
• Within GRASP there are nine principles. They are:
• Creator
• Information expert
• Low coupling
• Controller
• High cohesion
• Indirection
• Polymorphism
• Protected variations
• Pure fabrication

20
Creator
• The creator defines who instantiates what object.
• The Creator takes the responsibility of creating certain other objects.
• Dynamic creation of objects based upon easily interchangeable algorithms.
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 true (the more the better):
• B contains or aggregates A (in a collection)
• B records A
• B closely uses A
• B has the initializing data for A

21
Creator

• This pattern is probably the easiest to understand conceptually.


• There are a number of reasons why a class may take the responsibility of
creating another.
• The Creator might have information on how to create said object, or it might be
the class that uses the object most closely. These decisions will be largely
established in the initial design of the system, and other documents such as
UML diagrams will guide and inform the Creator pattern.

22
Creator
• An example of this is a printing-press. A printing-press creates printed pages
because it has the information (in the form of the type-set) to create these pages.
It would be silly to expect printed pages to come out of a microwave.
• The Creator Pattern allows for a lot of other best-practices to fall into place,
such as dependency injection and low-coupling. The Creator Pattern can be
used to enforce the logical design of a system. The Creator Pattern is of course a
parent to a whole family of patterns in the Gang of Four book, including the
very useful Factory, Prototype and Singleton patterns.
•.

23
Who creates the Squares?

Figure 17.3, page 283 24


How does Create pattern lead to
this partial Sequence diagram?

25
How does Create pattern develop
this Design Class Diagram (DCD)?

Board has a composite aggregation relationship with Square


• I.e., Board contains a collection of Squares

26
Discussion of Creator pattern

• Responsibilities for object creation are common


• Connect an object to its creator when:
• Aggregator aggregates Part
• Container contains Content
• Recorder records
• Initializing data passed in during creation

27
The Controller
• The Controller is responsible for handling the requests of actors.
• The Controller is the middle-man between your user clicking “Send” and your
back-end making that happen.
• The Controller knows how to interpret the actions of user-interfaces, and how to
connect those actions to behaviors in your system.
• This pattern allows user-interfaces to be separated cleanly from “business
objects”, and have both change independently of one another.
• Implicit in this is that a system can also support many different user-interfaces
at once, which is very groovy.

28
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)

29
The Controller

• We can imagine a controller as the steering wheel in a car, it connects the


intentions of a driver to the actions of the vehicle. Changing the engine of the
car does not need to change how the car is used at a high level. And likewise
replacing a steering wheel does not require any internal components to be
modified. Some cars even have multiple steering wheels.
• The Controller is also an important idiom in modern web development
frameworks, in forming a pillar of the Model-View-Controller architectural
pattern. Controllers are used in AngularJS, Ruby on Rails, Sails and more.

30
Controller
• A simple layered architecture has a user interface layer (UI) and a domain layer.
• Actors, such as the human player in Monopoly, generate UI events (such as clicking a button with a
mouse to play a game or make a move).
• The UI software objects (such as a JFrame window and a JButton) must process the event and cause the
game to play. When objects in the UI layer pick up an event, they must delegate the request to an object
in the domain layer.
The Expert
• Given a responsibility, what class must accomplish it.
• Assign the responsibility to the class that knows the necessary information
• As our systems grow, we might find that we are putting too much logic into our
controllers. This results in what we call “bloated controllers”. Bloated
controllers imply tight coupling in our system, which is bad.
• The Expert Pattern solves this by encapsulating information about a task
into a distinct class. This may sound a bit abstract, but let’s work through a
simple example. User-authentication is a common problem. We can have a user
that is logging in to have their username and password validated within our
system. With just a controller, this might look this:
• User Login →Controller →Database

32
Expert
• this transaction requires a lot of work on the part of the Controller.
Authentication may entail hashing, database look-ups and perhaps other
application-specific tasks. We therefore introduce an expert: Authentication
Module. This module knows precisely how to authenticate a user, and the
Controller need only delegate the authentication request to this module to know
that authentication will be handled correctly.
• Login Request → Controller → Authentication Module → Database
• In this way, the Expert pattern is very much like an expert in the real world.
When we wish to build a house, we might enlist the help of an architect. It is
within feasibility for a person to design their own house (and many people do),
but most of the time we would rather out-source this task. People have enough
to manage when building a house already, and an architect is certainly better
equipped to design houses.

33
Information Expert pattern

• This principle used to determine where to delegate responsibilities such as


methods, computed fields, and so on.
• Using the principle of information expert, a general approach to assigning
responsibilities is to look at a given responsibility, determine the information
needed to fulfill it, and then determine where that information is stored.
• Problem: How to assign responsibilities to object?
• Solution: Assign responsibility to the class that has the information necessary to
fulfill the responsibility.

34
Benefits and Contraindications
• Facilitates information encapsulation: why?
• Classes use their own info to fulfill tasks
• Encourages cohesive, lightweight class definitions.
But:
• Information expert may contradict patterns of Low Coupling and High
Cohesion
• Remember separation of concerns principle for large sub-systems
• Contraindication: –
• Conflict with late binding . Late binding is available only for the receiver
object
35
Benefits

• Information encapsulation is maintained since objects use their own information


to fulfill tasks. This usually supports low coupling, which leads to more robust
and maintainable systems.
• Behavior is distributed across the classes that have the required information,
thus encouraging more cohesive "lightweight" class definitions that are easier to
understand and maintain. High cohesion is usually supported (another pattern
discussed later).

36
Polymorphism
• according to the polymorphism principle, responsibility for defining the variation of
behaviors based on type is assigned to the type for which this variation happens.
• This is achieved using polymorphic operations.
• The user of the type should use polymorphic operations instead of explicit branching
based on type.

37
Polymorphism
• Problem:
• How to handle behaviour based on type (i.e., class), but not with an if or switch
statement? Polymorphism is also used to create pluggable software components.

• " When alternate behaviors are selected based on the type of an object, use
polymorphic method call to select the behavior, rather than use if statements to test the
type“
• Solution:
Polymorphism is realized by overriding a method from a super class or implementing
an interface. The implemented overridden methods are polymorphic in that a client
class uses the same method, but the behaviour depends on the type of the object being
referenced.

38
Example
• A possible set of two dimensional shapes include: circle, triangle, and square. Each of these
shapes has an area and a perimeter. The calculation of area and perimeter depend on the type of
shape.
• the getArea() varies by the type of shape, so we assign that responsibility to the subclasses.
• By sending message to the Shape object, a call will be made to the corresponding sub class
object – Circle or Triangle.

39
Protected variations

40
Protected variations

• 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.
• The protected variations pattern protects elements from the variations on other
elements (objects, systems, subsystems) by wrapping the focus of instability with an
interface and using polymorphism to create various implementations of this interface.
• It provides a well defined interface so that the there will be no affect on other units.
• Provides flexibility and protection from variations.
• Provides more structured design.
• Example: polymorphism, data encapsulation, interfaces
• Note: The term "interface" is used in the broadest sense of an access view; it does not
literally only mean something like a Java interface.

41
• Problem :
• What object should have the responsibility, when you do not want to violate High
Cohesion and Low Coupling, or other goals, but solutions offered by Expert (for
example) are not appropriate?
• Object - oriented designs are sometimes characterized by implementing as software
classes representations of concepts in the real - world problem domain to lower the
representational gap; for example a Sale and Customer class. However, there are many
situations in which assigning responsibilities only to domain layer software classes
leads to problems in terms of poor cohesion or coupling, or low reuse potential.
• 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.

42
Pure fabrication

• A pure fabrication is a class that does not represent a concept in the problem
domain, specially made up to achieve low coupling, high cohesion, and the
reuse potential thereof derived (when a solution presented by the information
expert pattern does not). This kind of class is called a "service" in domain-
driven design.

43
Benefits

• High Cohesion is supported because responsibilities are factored into a


finegrained class that only focuses on a very specific set of related tasks.
• Reuse potential may increase because of the presence of fine - grained Pure
Fabrication classes whose responsibilities have applicability in other
applications.

44
Low Coupling
• Problem: How to reduce the impact of change on software?

• Solution (advice): Assign responsibilities so that (unnecessary) coupling remains low.


Use this principle to evaluate alternatives.
• 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.

45
Benefits & Contraindications

• Understandability: Classes are easier


to understand in isolation
• Maintainability: Classes aren’t affected by changes in other components
• Reusability: easier to grab hold of classes
But:
• Don’t sweat coupling to stable classes (in libraries or pervasive, well-tested
classes)

46
High Cohesion

• Cohesion measures how functionally related the operations of a software


element are. It also measures how much work an object is doing. Note low
cohesion and bad coupling often go together.
• Problem: How to keep objects focused, understandable, and manageable,
and, as a side effect, support Low Coupling.
• Solution: Assign responsibilities so that cohesion remains high. Use this criteria
to evaluate alternatives.

47
Benefits & Contraindications
• Understandability, maintainability
• Complements Low Coupling

But:
• Avoid grouping of responsibilities or code into one class
or component to simplify maintenance by one person.
Why?
• Sometimes desirable to create less cohesive server
objects that provide an interface for many operations, due
to performance needs associated with remote objects and
remote communication
48
GRASP 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 desperate, and do not want to violate High Cohesion and
Low Coupling?
• Indirection
• Who, to avoid direct coupling?
• Protected variations :Law of Demeter (Don’t talk to strangers)
• Who, to avoid knowing about the structure of indirect objects?

49

Вам также может понравиться