52
GRASP CSC 440: Software Engineering Slide #1

GRASP - Northern Kentucky University · CSC 440: Software Engineering Slide #6 . Design Patterns . Pattern is a named problem/solution pair that can be applied in new contexts, …

  • Upload
    phamque

  • View
    213

  • Download
    1

Embed Size (px)

Citation preview

GRASP

CSC 440: Software Engineering Slide #1

CSC 440: Software Engineering Slide #2

Topics 1. Responsibilities and Methods 2. Interaction Diagrams 3. Design Patterns 4. GRASP Patterns

1. Information Expert 2. Creator 3. Low Coupling 4. High Cohesion 5. Controller

5. CRC Cards

Object-Oriented Design

Slide #3

Operation: enterItem(…)

Post-conditions:- . . .

Operation Contracts

Sale

date. . .

SalesLineItem

quantity

1..*1 . . .

. . .

Domain Model

Use-Case Model

Design Model: Register

enterItem(itemID, quantity)

: ProductCatalog

d = getProductDescription(itemID)

addLineItem( d, quantity )

: Sale

Require-ments

Business Modeling

Design

Sample UP Artifact Relationships

: System

enterItem(id, quantity)

Use Case Text

System Sequence Diagrams

makeNewSale()

system events

Cashier

Process Sale

: Cashier

use case

names

system operations

Use Case Diagram

SupplementarySpecification

Glossary

starting events to design for, and detailed post-condition to satisfy

Process Sale

1. Customer arrives ...2. ...3. Cashier enters item identifier.

inspiration for names of some software domain objects

functional requirements that must be realized by the objects

ideas for the post-conditions

Register

...

makeNewSale()enterItem(...)...

ProductCatalog

...

getProductDescription(...)...

1*

non-functional requirements

domain rules

item details, formats, validation

CSC 440: Software Engineering Slide #4

Responsibilities Contracts or obligations of an object/class

Doing responsibilities Doing something itself: create an object or perform

calculation. Initiate action in other objects. Control or coordinate actions in other objects.

Knowing responsibilities Knowing about private encapsulated data. Knowing about related objects. Knowing about things it can derive or calculate.

CSC 440: Software Engineering Slide #5

Responsibilities and Methods Assign responsibilities to classes of objects during object design

doing example: a Sale is responsible for creating SalesLineItems

knowing example: a Sale is responsible for knowing its total create a getTotal() method for Sale objects, which may

require collaboration with other objects, such as sending getSubtotal() message to each SalesLineItem

CSC 440: Software Engineering Slide #6

Design Patterns Pattern is a named problem/solution pair that can be applied in new contexts, with advice on how to apply it in novel situations and discussion of its trade-offs.

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

CSC 440: Software Engineering Slide #7

GRASP Patterns General Responsibility Assignment Software Patterns

Describe fundamental principles of object design and responsibility assignment.

The Five GRASP Patterns we’ll consider today: 1. Information Expert 2. Creator 3. Low Coupling 4. High Cohesion 5. Controller

CSC 440: Software Engineering Slide #8

Information Expert Pattern Name: Information Expert (or 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.

CSC 440: Software Engineering Slide #9

Expert Example Start assigning responsibilities by clearly stating the responsibility

“Who should be responsible for knowing the grand total of a sale?”

Information Expert patterns tells us to look for the class that has information to determine total

1. Look for relevant classes in the Design Model 2. Look in the Domain Model for inspiration to create

an appropriate software class.

CSC 440: Software Engineering Slide #10

Expert Example Since we’re doing our first responsibility assignment, we have no Design Model and must reference our Domain Model.

Sale

datetime

SalesLineItem

quantity

ProductSpecification

descriptionpriceitemID

Described-by*

Contains

1..*

1

1

CSC 440: Software Engineering Slide #11

Expert Example What information do we need to know grand total?

Need all SalesLineItem subtotals Which conceptual class in Domain Model can obtain all the subtotals?

The Sale class. Therefore Sale is the Information Expert for this responsibility.

CSC 440: Software Engineering Slide #12

Expert Example Construct partial interaction and class diagrams for Sale class and getTotal method.

Sale

datetime

getTotal()

:Salet := getTotal()

New method

CSC 440: Software Engineering Slide #13

Expert Example Connect Sale class to SalesLineItem collection to show details of how getTotal is performed.

Sale

datetime

getTotal()

SalesLineItem

quantity

getSubtotal()New method

1 *: st := getSubtotal(): Salet := getTotal()

*:SalesLineItem

:SalesLineItem

CSC 440: Software Engineering Slide #14

Expert Example How does SalesLineItem know item price to calculate subtotals?

Sale

datetime

getTotal()

SalesLineItem

quantity

getSubtotal()

ProductSpecification

descriptionpriceitemID

getPrice()New method

:ProductSpecification

1.1: p := getPrice()

1 *: st := getSubtotal(): Salet := getTotal()

*:SalesLineItem

:SalesLineItem

CSC 440: Software Engineering Slide #15

Expert: Example Summary To fulfill responsibility of knowing sale’s total, three responsibilities were assigned to three new design classes as follows:

Design Class Responsibility Sale knows sale total SalesLineItem knows line item subtotal

ProductSpecification knows product price

CSC 440: Software Engineering Slide #16

Expert: Discussion Information Expert is a basic guiding principle used

continuously in object design. Expert is not meant to be obscure or fancy idea; it

expresses the common “intuition” that objects do things related to information they have.

Leads to designs where software object does things that are normally done to the inanimate real world object it represents Sale calculates total itself as a software object Person would calculate total of sale (perhaps with

assistance) in real world

CSC 440: Software Engineering Slide #17

Expert: Discussion—Collaboration Fulfillment of a responsibility often requires information that is spread across different classes of objects.

Many partial Information Experts collaborate in task ex: Sales total required collaboration of 3 classes of

objects. Whenever information is spread across different objects, they will need to interact via messages to share the work.

People collaborate in similar ways in real world endeavors.

CSC 440: Software Engineering Slide #18

Expert: Contraindications Situations exist where a solution suggested by Expert is undesirable, usually because of problems in coupling and cohesion. Example: Who is responsible for saving Sale in the database?

Expert suggests Sale is responsible since it has the information to save.

Problem: Sale now contains database logic and is no longer focused on the application logic of what a Sale is and does.

Violation of basic architectural principle: design for a separation of major system concerns, such as application and database logic.

See High Cohesion and Low Coupling design patterns later for solutions.

CSC 440: Software Engineering Slide #19

Expert: 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, encouraging more cohesive “lightweight” class definitions that are easier to understand and maintain.

High cohesion is usually supported.

CSC 440: Software Engineering Slide #20

Creator Pattern Name: Creator 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 an object-oriented system. Consequently, 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.

CSC 440: Software Engineering Slide #21

Creator Pattern Name: Creator Solution: Assign class B the responsibility to create an instance of class A if one or more of the following is true :

B contains or aggregates A. B records A. B closely uses A. B has initializing data for A.

CSC 440: Software Engineering Slide #22

Creator: Example Who should be responsible for creating a SalesLineItem instance?

Sale

datetime

SalesLineItem

quantity

ProductSpecification

descriptionpriceitemID

Described-by*

Contains

1..*

1

1

CSC 440: Software Engineering Slide #23

Creator: Example Since a Sale aggregates many SalesLineItem objects, Creator suggests that Sale should be responsible for SalesLineItem creation.

Add a makeLineItem() method to Sale class.

: Register : Sale

makeLineItem(quantity): SalesLineItemcreate(quantity)

CSC 440: Software Engineering Slide #24

Creator: Discussion Creator guides assigning responsibilities related to creation of objects, a very common task. The basic intent of the Creator pattern is to find a creator that needs to be connected to the created object in any event. Examples:

Aggregator aggregates Part Container contains Content Recorder records Recorded

Sometimes a creator is found by looking for the class that has the initializing data that will be passed in during creation, an example of the Expert design pattern.

CSC 440: Software Engineering Slide #25

Creator: 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.

In these instances, delegation of creation to a helper class called a Factory is preferred.

CSC 440: Software Engineering Slide #26

Creator: Benefits Low coupling is supported, reducing maintenance dependencies and increasing opportunity for reuse.

CSC 440: Software Engineering Slide #27

The Problem of High Coupling Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other element.

Highly coupled classes rely on details of many other classes, leading to problems such as:

Changes in related classes force local changes. Harder to understand in isolation. Harder to reuse because its use requires additional

presence of classes on which it’s dependent.

CSC 440: Software Engineering Slide #28

Low Coupling Pattern Name: Low Coupling Problem: How to support a low dependency, low change impact, and increased reuse? Solution: Assign a responsibility in such a way that coupling remains low.

CSC 440: Software Engineering Slide #29

Low Coupling: Example

: Register p : Payment

:Sale

makePayment() 1: create()

2: addPayment(p)

: Register :Sale

:Payment

makePayment() 1: makePayment()

1.1. create()

Design 1:

Design 2:

CSC 440: Software Engineering Slide #30

Low Coupling Is coupling higher when Payment is created by Register or by Sale?

Sale is coupled to Payment in both designs Design 1 adds coupling of Payment to Register

Therefore Design 2 has lower coupling.

CSC 440: Software Engineering Slide #31

Low Coupling: Discussion Low Coupling is a principle to use in evaluating all design decisions.

No absolute measure of when coupling is too high exists.

Low Coupling cannot be considered in isolation from other patterns like Expert and High Cohesion.

Low Coupling is more important in design elements where you expect future change, such as interface to 3rd party tax calculators in NextGen POS project.

CSC 440: Software Engineering Slide #32

Low Coupling: Contraindications High coupling to pervasive elements, like your language’s standard library, isn’t a major problem because such elements are stable and widespread.

CSC 440: Software Engineering Slide #33

Low Coupling: Benefits Classes are not affected by changes in other

components. Classes are simple to understand in isolation. Classes are convenient to reuse.

CSC 440: Software Engineering Slide #34

The Problem of Low Cohesion Cohesion is a measure of how strongly related and focused the responsibilities of an element are.

Classes with low cohesion perform many unrelated tasks or do too much work, resulting in the following issues:

Hard to comprehend. Hard to reuse. Hard to maintain. Delicate; constantly affected by change.

CSC 440: Software Engineering Slide #35

High Cohesion Pattern Name: High Cohesion Problem: How to keep complexity manageable? Solution: Assign a responsibility in such a way that cohesion remains high.

CSC 440: Software Engineering Slide #36

High Cohesion: Example Should Register create Payment?

: Register : Sale

addPayment( p )

p : Paymentcreate()makePayment()

CSC 440: Software Engineering Slide #37

High Cohesion: Example Or should Sale create Payment?

: Register : Sale

makePayment() : Paymentcreate()

makePayment()

CSC 440: Software Engineering Slide #38

High Cohesion: Example Register creating both Payment and Sale isn’t too many responsibilities for one class.

But what if we continue giving Register the responsibility to create most of the objects in our POS system, since it’s the center of control for our primary use cases?

The second design provides both Low Coupling and High Cohesion so we prefer it.

CSC 440: Software Engineering Slide #39

Levels of Cohesion Very Low Cohesion – A class is responsible for many different unrelated functional areas.

Low Cohesion – A class has sole responsibility for a complex task in one functional area.

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.

High Cohesion – A class has moderate responsibilities in one functional area and collaborates with other classes to fulfill tasks.

CSC 440: Software Engineering Slide #40

How do you know if a class has High Cohesion? No definite measure, but heuristics exist:

Small number of methods. Methods have highly related functionality. Doesn’t do too much work. Collaborates with other objects to perform large tasks.

CSC 440: Software Engineering Slide #41

High Cohesion: Discussion High Cohesion is a principle to use in evaluating all design decisions.

No absolute measure of when cohesion is too low exists.

High Cohesion cannot be considered in isolation from other patterns like Expert and Low Coupling.

Bad cohesion usually begets bad coupling, and vice versa.

CSC 440: Software Engineering Slide #42

High Cohesion: Contraindications Distributed objects may call for larger classes and

methods due to the higher overhead of making remote procedure calls.

CSC 440: Software Engineering Slide #43

High Cohesion: Benefits Clarity and ease of comprehension of design increased. Maintenance and enhancements simplified. Low coupling is often supported. Increased reuse potential, since entire component is

focused on one task.

CSC 440: Software Engineering Slide #44

Controller Pattern Name: Controller Problem: Who should be responsible for handling a system input event? Solution: Assign the responsibility for receiving or handling a system event message to a class representing one of the following choices:

Represents the overall system, device, or subsystem (facade controller)

Represents a use case scenario within which the system event occurs, often named <UseCaseName>Controller

CSC 440: Software Engineering Slide #45

Controller: Example

CSC 440: Software Engineering Slide #46

Controller: Example Who should receive enterItem events?

Register and POSSystem represent entire system or subsystem.

ProcessSaleHandler or ProcessSaleSession would represent the particular use case involved.

:RegisterenterItem(id, quantity)

:ProcessSaleHandleenterItem(id, quantity)

CSC 440: Software Engineering Slide #47

High Application/Presentation Coupling

Controller: Example Solution

Slide #48

CSC 440: Software Engineering Slide #49

Controller: Discussion Controller is not a user interface element.

It receives system events from UI objects. Controller delegates work to other objects

It doesn’t do much work itself. It may ensure that each step of use case is performed in

order or retain state between steps.

CSC 440: Software Engineering Slide #50

Controller: Discussion Facade Controller

Represents an abstraction of a physical unit such as Register or logical unit such as ChessGame.

Suitable when few system events exist or if it’s not possible for UI objects to redirect system event messages to specific use case controllers.

Use Case Controller Different controller for each use case. Not a domain object; a pure software object. Use when Facade Controller would result in high coupling

or low cohesion.

CSC 440: Software Engineering Slide #51

Controller: Discussion User-interface objects like windows, widgets, and web

forms should not have responsibility for performing system tasks.

Separate presentation and application logic.

CSC 440: Software Engineering Slide #52

Controller: Benefits Increased potential for reuse.

Ensures application logic not handled in presentation layer so can be re-used with different interface. Example: Cashier GUI mode. Statistics-gathering batch mode.

Allows us to reason about the use case. All information about use case state and order of

operations stored in one class.