91
GRASP: Designing Objects With Responsibilities Chapter 17 Applying UML and Patterns -Craig Larman

GRASP: Designing Objects With Responsibilities

  • Upload
    gannon

  • View
    29

  • Download
    0

Embed Size (px)

DESCRIPTION

GRASP: Designing Objects With Responsibilities. Chapter 17 Applying UML and Patterns -Craig Larman. Designing Objects With Responsibilities. - PowerPoint PPT Presentation

Citation preview

Page 1: GRASP: Designing Objects With Responsibilities

GRASP: Designing Objects With Responsibilities

Chapter 17

Applying UML and Patterns

-Craig Larman

Page 2: GRASP: Designing Objects With Responsibilities

Designing Objects With Responsibilities

2

“Identify requirements, create a domain model and define

dynamic behaviour , define messages to meet

requirements , add methods to the software classes …”

Too Simple!

How do we assign responsibilities to classes?

What methods belong where?

Page 3: GRASP: Designing Objects With Responsibilities

Object Design : Input Use case text

• Defining the behavior System sequence diagram

• Identifying the system operation messages The operation contract

• Stating events to design for, and detailed post-condition to satisfy Supplementary specification

• Defines non-functional goals Glossary

• Data format, data related with UI and database Domain model

• initial attempt of software object in the domain layer of software architecture

3

Page 4: GRASP: Designing Objects With Responsibilities

Fig. 17.1 UP artifacts influencing OO design

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

Page 5: GRASP: Designing Objects With Responsibilities

Responsability Driven Design-RDD

Design of behavior implies assigning responsibilities to software

classes.

Responsibilities are assigned to classes of objects during object

design.

Responsibility is a contract or obligation of a class

• What must a class “know”? [knowing responsibility]

• What must a class “do”? [doing responsibility]

5

Page 6: GRASP: Designing Objects With Responsibilities

Doing Responsability

What must a class “do”? [doing responsibility]

Take action (create an object, do a calculation)

Initiate action in other objects

Control/coordinate actions in other objects

Doing responsibilities are implemented by means of methods

Methods fulfill responsibilities alone or through collaboration with other

objects and methods.Ex: A Sale is responsible for creating SalesLineItems” (doing)

6

Page 7: GRASP: Designing Objects With Responsibilities

Responsibilities and methods : create

: Sale

makePayment(cashTendered)

: Paymentcreate(cashTendered)

abstract, implies Sale objects have a responsibility to create Payments

Sale objects are given a responsibility to create Payments.

The responsibility is invoked with a makePayment message

Page 8: GRASP: Designing Objects With Responsibilities

knowing responsibility

What must a class “know”? [knowing responsibility]

• Private encapsulated data

• Related objects

• Things it can derive or calculate

Knowing responsibilities are related to attributes, associations in

the domain model.

Domain model illustrates attributes and associations => inspires the “knowing” responsibilities.

Ex : a Sale is responsible for knowing its total” (knowing)

8

Page 9: GRASP: Designing Objects With Responsibilities

Responsibilities and attribute

9

:Bookd := getDueDate()

getDueDate message impliesBook has responsibility forknowing its due date.

Page 10: GRASP: Designing Objects With Responsibilities

RDD and Collaboration

10

Responsibilities are implemented by

methods

Some methods act alone and do a task

Some collaborate with other objects to

fulfill their responsibility.Example:

Sale class has getTotal() method,

the getTotal() collaborates with

SalesLineItem objects to get the

subtotal through getSubtotal()

methods

Page 11: GRASP: Designing Objects With Responsibilities

Software patternWhat is a software pattern?

A design pattern is a general reusable and

proven solution to a commonly occurring

problem in software design.

Craig Larman: “ a pattern is a named

problem/solution pair that can be applied in

new contexts, with advice on how to apply it in

novel situations”

11

Page 12: GRASP: Designing Objects With Responsibilities

Well‐known Pattern Families

12

GRASP = General Responsibility Assignment Software

Patterns

Describe fundamental principles for assigning

responsibilities to classes and for designing

interactions between classes

GoF: Gang of Four Design Patterns : 23 pattrens

We’ll cover with GRASP

Page 13: GRASP: Designing Objects With Responsibilities

GRASP Patterns9 GRASP patterns , but we start with the first five

• Information Expert

• Creator

• Controller

• Low Coupling

• High Cohesion

• Polymorphism

• Pure Fabrication.

• Indirection.

• Don’t Talk to Strangers13

Page 14: GRASP: Designing Objects With Responsibilities

Creator

Page 15: GRASP: Designing Objects With Responsibilities

Creator principle

• Problem: Who creates an A object

• Solution: Assign class B the responsibility to

create an instance of class A if one of these is

true B “contains or aggregate ” A

B “records” A

B “closely uses” A

B “ has the Initializing data for ” A

15

Page 16: GRASP: Designing Objects With Responsibilities

Creator principleB “has the Initializing data for ” A that will be passed to

A when it is created.

•Often initiation is done using a constructor with parameters.

e.g. a Payment instance, when created

needs to be initialized with the Sale total.

•Sale class knows Sale total. Good candidate for creating Payment is Sale.

If more than one of the above applies, prefer a class B which aggregates or contains A.

16

Page 17: GRASP: Designing Objects With Responsibilities

Creator Pattern in Monoply

17

Page 18: GRASP: Designing Objects With Responsibilities

Problem Who should create a SalesLineItem?

Sale

time

SalesLineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by*

Contains

1..*

1

1

Page 19: GRASP: Designing Objects With Responsibilities

19

Page 20: GRASP: Designing Objects With Responsibilities

Creating a SalesLineItem: Register : Sale

makeLineItem(quantity)

: SalesLineItemcreate(quantity)

Sale objects are given a responsibility to create SaleLineItem. The responsibility is invoked with a makeLineItem message

Page 21: GRASP: Designing Objects With Responsibilities

Creating a SalesLineItem

21

Page 22: GRASP: Designing Objects With Responsibilities

Why Catalog is reating a Book ?

:Catalog

makeBook(title)

1: create(title):Book

by Creator

Page 23: GRASP: Designing Objects With Responsibilities

Information Expert

Page 24: GRASP: Designing Objects With Responsibilities

Information Expert

Problem : What is a basic principle by which to assign responsibilities to objects?

Solution (advice ) : Assign a responsibility to the information

expert , that is the class with the information necessary

to fulfill the responsibility.

“Objects do things related to the information they have.”

Page 25: GRASP: Designing Objects With Responsibilities

Applying Expert in POS ApplicationStart assigning responsibilities by

clearly stating the responsibility. Who should be responsible for

knowing the grand total of a sale?

Page 26: GRASP: Designing Objects With Responsibilities

Sale

time

SalesLineItem

quantity

ProductDescription

descriptionpriceitemID

Described-by*

Contains

1..*

1

1

Who should be responsible for knowing/getting the grand total of a sale?

Page 27: GRASP: Designing Objects With Responsibilities

27

Who responsible for knowing the grand total of a sale?

Page 28: GRASP: Designing Objects With Responsibilities

Partial interaction and class diagrams

Sale

time...

getTotal()

:Salet = getTotal

New method

Add a Sale class to the Design Model. Express responsibility of knowing the total of a sale with the

method named getTotal.

What information do we need to know to determine the line item subtotal?

Sale knows about neighbours (associations), SaleLineitems who is responsible for knowing its subtotal

Page 29: GRASP: Designing Objects With Responsibilities

SalesLineItem is Expert for Subtotal

Sale

time...

getTotal()

SalesLineItem

quantity

getSubtotal()New method

1 *: st = getSubtotal: Salet = getTotal lineItems[ i ] : SalesLineItem

this notation will imply we are iterating over all elements of a collection

How does the SalesLineItem find out the product price?

SaleLineItem knows about neighbours ( ProductDescription) to get the price.

Page 30: GRASP: Designing Objects With Responsibilities

ProductDescription is Expert for PriceSale

time...

getTotal()

SalesLineItem

quantity

getSubtotal()

ProductDescription

descriptionpriceitemID

getPrice()New method

:ProductDescription

1.1: p := getPrice()

1 *: st = getSubtotal: Salet = getTotal lineItems[ i ] :SalesLineItem

“Partial” information experts collaborate to fulfill the responsibility.

Page 31: GRASP: Designing Objects With Responsibilities

31

:Library

borrowResource(callNum)

1: r := getResource(callNum): Resource:Catalog

Catalog is an information expert onfinding and returning a resource,based on a call number. It logicallycontains all of them.

by Expert

What class should be responsible forknowing a resource, given a call number?

Another Example

Page 32: GRASP: Designing Objects With Responsibilities

Low Coupling Principle

Page 33: GRASP: Designing Objects With Responsibilities

“Low Coupling” Principle

33

Problem: How to support low dependency, Low change impact, and increased reuse?

Solution: Assign responsibilities so that coupling remains low. Use this principle to evaluate alternatives.

Coupling is a measure of how strongly one class is

• connected to,

• has knowledge of, or

• relies upon other classes.

Page 34: GRASP: Designing Objects With Responsibilities

What is a coupling ?

34

Coupling between classes is dependency of one class

on another class

Common form of coupling from Class A to Class B are:

Class A has an attribute (data member or instance

variable) that refers to a Class B instance, or

Class B itself.

Page 35: GRASP: Designing Objects With Responsibilities

What is a coupling ?

35

Common form of coupling from Class A to Class B are:

Class A has a method which references an

instance of Class B, or Class B itself, by any

means. These typically include a parameter or

local variable of type Class B, or the object

returned from a message being an instance of

Class B.

Page 36: GRASP: Designing Objects With Responsibilities

What is a coupling (continued) ?

36

Common form of coupling from Class A to Class B are:

Class A is a direct or indirect subclass of Class B.

Class B is an interface, and Class A implements

that interface.

Page 37: GRASP: Designing Objects With Responsibilities

Common Forms of Coupling in OO Languages

Type X has an attribute (data member, instance variable) that refers to type Y or an instance of Y.

An object of type X calls on services of a type Y object.

Type X has a method that references an instance of type Y (e.g., parameter, local variable, object returned from a method).

Type X is a subclass of type Y. Type X implements the interface Y.

Page 38: GRASP: Designing Objects With Responsibilities

Low Coupling - POS Case Study

What class should be responsible for creating a Payment instance and associating it with the Sale?• Register?

• Sale?

Creator pattern suggests Register should create the Payment.• A register records a payment in the real world.

Page 39: GRASP: Designing Objects With Responsibilities

What if Register creates Payment

: Register p : Payment

:Sale

makePayment() 1: create()

2: addPayment(p)

Register is coupled to both Sale and Payment.

Page 40: GRASP: Designing Objects With Responsibilities

What if Sale creates Payment ?

: Register :Sale

:Payment

makePayment() 1: makePayment()

1.1. create()

Assuming that the Sale must eventually be coupled to knowledge of a Payment, having Sale create the Payment does not increase coupling.

NB : Low Coupling and Creator may suggest different solutions.

Page 41: GRASP: Designing Objects With Responsibilities

Controller Pattern

Page 42: GRASP: Designing Objects With Responsibilities

Controller Pattern

42

UI layer does not contain any business logic

Problem:How to connect UI layer to the business logic layer?

Solution:If a program receive events from external sourcesother than its graphical interface, add an event classto decouple the event source(s) from the objectsthat actually handle the events.

Page 43: GRASP: Designing Objects With Responsibilities

Controller Pattern

What first object beyond the UI layer receives and coordinates (“controls”) a system operation message?

Solution: Assign the responsibility to a class that represents one of the following options:

Page 44: GRASP: Designing Objects With Responsibilities

Options for Control Responsibility

1. Represents the overall system or a root object.

e.g., an object called System or Register

Suitable when there are not too many system events or when UI cannot choose between multiple controllers.

2. A controller for each use case

e.g. processSaleHandler

Page 45: GRASP: Designing Objects With Responsibilities

Controller choices ?

:RegisterenterItem(id, quantity)

:ProcessSaleHandlerenterItem(id, quantity)

Register (POS Terminal) is a specialized device with software running on it.

ProcessSaleHandler represents a receiver of all system events of a use case scenario.

Controllers

Page 46: GRASP: Designing Objects With Responsibilities

What should be Controller for enterItem?

Which class of object should be responsible for receiving this system 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)

UI Layer

Domain Layer

system operation message

Page 47: GRASP: Designing Objects With Responsibilities

Bad Design

Cashier

:SaleJFrame

actionPerformed( actionEvent )

:Sale1: makeLineItem(itemID, qty)

UI Layer

Domain Layer

It is undesirable for an interfacelayer object such as a window to get involved in deciding how to handle domain processes.

Business logic is embedded in the presentation layer, which is not useful.

SaleJFrame should not send this message.

presses button

Page 48: GRASP: Designing Objects With Responsibilities

Good Design

actionPerformed( actionEvent )

:Register

: Cashier

:SaleJFrame

presses button

1: enterItem(itemID, qty)

:Sale1.1: makeLineItem(itemID, qty)

UI Layer

Domain Layer

system operation message

controller

Controller should delegate the work that needs to be done to other objects.

Page 49: GRASP: Designing Objects With Responsibilities

Use Case Controller A use case controller handles system events for

a single use case.

• Can maintain information about the state of the use case.

• Different controller for each use case. Not a domain object, but artificial construct to

support the system. Use when there are many system events.

• Factors handling into separate classes.

Page 50: GRASP: Designing Objects With Responsibilities

Controller

:LibrarianborrowResource(callNum)

:BorrowResourceHandler

borrowResource(callNum)

role controller

use case controller

Page 51: GRASP: Designing Objects With Responsibilities

Controller: Benefits

51

Increased potential for reuse

Ensures that the application logic is not handled in the interface layer.

Thus, the external event raisers are independent of internal event

handlers

Plug & Play interfaces

Since the interface is not bound to the controllers, it can be replaced

or updated without much impact

Verifying the reasoning of the use case

Allows us to verify that the system operations occur in a logical

sequence. For example: makePayment() is not called before

endSale()

Page 52: GRASP: Designing Objects With Responsibilities

High Cohesion

Page 53: GRASP: Designing Objects With Responsibilities

High Cohesion

53

A class with low cohesion does too much unrelated work and are:

• Hard to comprehend• Hard to reuse.• Hard to maintain.• Delicate and constantly

affected by changeCohesion is a measure of how strongly related the responsibilities of an element (classes, subsystems) are.

Page 54: GRASP: Designing Objects With Responsibilities

High Cohesion Problem

• How to keep complexity manageable?

Solution

• Assign a responsibility so that cohesion remains high

Page 55: GRASP: Designing Objects With Responsibilities

Reduced cohesion of Register(creator pattern)

: Register : Sale

addPayment( p )

p : Paymentcreate()makePayment()

Low cohesion:

Register is taking part of the responsibility for fulfilling “makePayment” operation and many other unrelated responsibility ( 50 system operations all received by Register).then it will become burden with tasks and become incohesive

Page 56: GRASP: Designing Objects With Responsibilities

Better solutionHigher Cohesion and Lower Coupling

: Register : Sale

makePayment()

: Paymentcreate()

makePayment()

Solution:

Delegate the payment creation responsibility to “Sale” to support high cohesion

Page 57: GRASP: Designing Objects With Responsibilities

Conclusion

Like Low Coupling, High Cohesion is a principle to keep in mind during all design decisions

It is important to evaluate design constantly with respect to GRASP principles, regardless of the design result.

57

Page 58: GRASP: Designing Objects With Responsibilities

Object Design: startUp Initial system operation

Delay until all other system operations have been considered

What objects need to be there through out the use case

What associations need to be there through out the use case

Create a set of domain objects that need to be there to support the

use

case execution

Find a suitable initial object and request that object to create a set of

other objects

Do the initialization design last 58

Page 59: GRASP: Designing Objects With Responsibilities

Object Design Examples with GRASP

Chapter 18Applying UML and Patterns

Craig Larman

Page 60: GRASP: Designing Objects With Responsibilities

60

Page 61: GRASP: Designing Objects With Responsibilities

Use-Case Realizations

UML interaction diagrams are used to

illustrate use-case realizations.

Design operations of the SSD

Principles and Patterns can be applied during

this design work.

Which object has which responsibility?

Page 62: GRASP: Designing Objects With Responsibilities

Domain Model and Use-Case Realization

Some of the software objects that interact via messages in the

interaction diagrams are inspired from the Domain Model.

• The existing domain model is not likely to be perfect. Errors

and omissions are to be expected.

• You will discover new conceptual classes that were

previously missed, ignore conceptual classes that were

previously identified, and do likewise with associations and

attributes.

Page 63: GRASP: Designing Objects With Responsibilities

Interaction Diagrams

Your System Sequence Diagram list the

system events.

Create a separate diagram for each system

operation(all events of the use case) under

development in the current iterative step.

If the diagram gets complex, split it into

smaller diagrams.

Page 64: GRASP: Designing Objects With Responsibilities

Multiple Sequence Diagrams (

Multiple sequence diagrams and system event message handling.

Page 65: GRASP: Designing Objects With Responsibilities

Use-case Realizations for NextGen Iteration

Explore the choices and decisions made while designing a use-case realization, with objects based on the GRASP patterns.• No magic in the creation of well designed

ID’s.

• Construction of ID’s is made on justifiable principles.

Page 66: GRASP: Designing Objects With Responsibilities

66

System Operations of POS Application

Page 67: GRASP: Designing Objects With Responsibilities

Interaction Diagrams and System Events

In the current iteration of PoS application, we are considering two use-cases and their associated system events:Process Sale

makeNewSaleenterItemendSalemakePayment

Start Up !!!!!!!startUp

Page 68: GRASP: Designing Objects With Responsibilities

Object Design : Contract

Name : makeNewSale() Responsibilities : Make a new sale for a cashier

to request to start a new sale, after a customer has arrived with things to buy.

Cross-References: Use Cases : Process Sale Pre-Conditions : None Post-Conditions : A sale instance was created.The sale instance was associated with the

register . Attributes of the sale instance were initialized.

Page 69: GRASP: Designing Objects With Responsibilities

Choosing the Controller Class

Our design choice involves choosing the controller for the system operation message

Here are some choices:

• Represents the overall system, device, or subsystem: Register,

• Represents a handler of all system events of a use-case scenario : ProcessSaleHandler.

From those choices, we choose the register as our controller

Page 70: GRASP: Designing Objects With Responsibilities

Creating a New Sale

A software sale object must be created, and the GRASP creator pattern suggests assigning the responsibility for creation to a class that aggregates, contains, or records the object to be created.

The register is a good choice to create the sale object by the creator pattern.

Page 71: GRASP: Designing Objects With Responsibilities

Creating a New Sale

Page 72: GRASP: Designing Objects With Responsibilities

Object Design : enterItem

Name: enterItem(itemID : itemID,quantity : integer)

Responsibilities : Enter sale of an item and add it to the sale. Display the item description and price.

Cross References : Use-Cases : ProcessSale.

Pre-Conditions : There is an underway sale.

Page 73: GRASP: Designing Objects With Responsibilities

Object Design : enterItem

Post-Conditions

• sli was associated with current sale.(association formed)

• sli.quantity became quantity.(attribute modification)

• sli was associated with a ProductSpecification, based on itemID match.(association formed), that is also should find its ProductSpecification

Page 74: GRASP: Designing Objects With Responsibilities

Creating a new SalesLineItem

The contract post condition indicate a responsibility to create a SalesLineItem instance.

A Sale contains SalesLineItem objects.• By creator pattern, the sale is an appropriate

candidate for creating Lineitems. GRASP creator pattern

• Assign the responsibility for creation to a class that aggregates, contains or records.

Page 75: GRASP: Designing Objects With Responsibilities

Finding a product specification

The SalesLineItem needs to be associated with the ProductSpecification that matches the incoming itemID.

Who should be responsible for looking up the ProductSpecification based on the itemID match?

By the Expert pattern, ProductCatalog is a good candidate for the responsibility, since it logically contains all the ProductSpecifications.

Page 76: GRASP: Designing Objects With Responsibilities

Visibility to a product catalog Who should send the Specification message to the

ProductCatalog to ask for a ProductSpecification?• Assumption: A Register and a ProductCatalog

instances were created during the initial Start Up use-case, and there is a permanent connection between them.

Based on this assumption, then it is possible to the

Register to send the specification message (using reference to productCatalog) to the ProductCatalog.

Page 77: GRASP: Designing Objects With Responsibilities
Page 78: GRASP: Designing Objects With Responsibilities

Object Design : endSale Contract

Name : endSale() Responsibilities : Record that it is the end of

entry of sale items, and display sale total. Cross References : Use Cases : Process Sale Exceptions : If a sale is not underway,

indicate that it was an error. Pre-Conditions : There is an underway sale. Post-Conditions : sale.isComplete became

true.

Page 79: GRASP: Designing Objects With Responsibilities

Choosing the Controller Class

Based on the Controller Pattern, as for enterItem, we will continue to use register as a controller.

Page 80: GRASP: Designing Objects With Responsibilities

Setting the Sale.isComplete attribute

We will continue to use register as a controller

The contract post-condition state:Sale.isComplete became true.As always, Expert should be the first pattern considered unless it is a controller or creation problem (which is not).Who should be responsible for setting the Sale.isComplete attribute of the Sale to true.

• By Expert, it should be the Sale itself.

Page 81: GRASP: Designing Objects With Responsibilities

Communication Diagram : endSale

Setting the Sale.isComplete attribute (2)

Page 82: GRASP: Designing Objects With Responsibilities

Constraints and Notes

Page 83: GRASP: Designing Objects With Responsibilities

Object Design:makePayment

Choosing the Controller Class Based on the Controller GRASP pattern, as

for enterItem, we will continue to use Register as a controller.

It is common to use the same controller throughout a use case.

Page 84: GRASP: Designing Objects With Responsibilities

Creating the Payment

Register – makePayment Communication diagram

Page 85: GRASP: Designing Objects With Responsibilities

Logging the Sale

Who should be responsible for knowing the complete sale.

Page 86: GRASP: Designing Objects With Responsibilities

Logging a completed sale

Perhaps we did not think of a sale ledger early, but now we have.

If it is not chosen, it would be ideally added to the domain model as well.

Fortunately, iterative development provides a life-cycle for continual change.

This kind of discovery and change during design work is to be expected.

Page 87: GRASP: Designing Objects With Responsibilities

Logging a Completed Sale

Page 88: GRASP: Designing Objects With Responsibilities

Calculating the Balance

Who is responsible for knowing the balance? To calculate the balance, the Sale and

Payment cash tendered are required. Therefore, Sale and Payment are partial

experts for solving the problem.

Page 89: GRASP: Designing Objects With Responsibilities

Calculating the Balance

Page 90: GRASP: Designing Objects With Responsibilities
Page 91: GRASP: Designing Objects With Responsibilities

Questions ?

91