Software Design CS 406 Software Engineering I Fall 2001

Preview:

DESCRIPTION

Software Design CS 406 Software Engineering I Fall 2001. Aditya P. Mathur. Last update: October 2, 2001. Organization. Part I: Design principles and process Part II: OO Design Part III:Design Patterns Part IV: Special topics. Learning Objectives. - PowerPoint PPT Presentation

Citation preview

Software DesignCS 406 Software Engineering I

Fall 2001

Aditya P. Mathur

Last update: October 2, 2001

October 2, 2001 Software Design 2

Organization

Part I: Design principles and process

Part II: OO DesignPart III: Design PatternsPart IV: Special topics

October 2, 2001 Software Design 3

Learning Objectives

To understand and be able to apply the basic principles of software design. (GRASP patterns).

To learn techniques and tools for Object-Oriented Design.

• Interaction diagrams• Class diagrams• State diagrams

To learn notations for representing a design.

October 2, 2001 Software Design 4

Models during the Design Phase

Class model Object behavior model

Design state model

Interaction Diagrams: Collaboration diagrams

Sequence diagrams

Contracts formethods and operations

Static structure diagrams

State diagrams for classes

October 2, 2001 Software Design 5

A collaboration diagram

:classAinstance

2: message3()

1: message2()

message1()

:classBinstance

message1() is sent to an instance of class A.message2() and message3() are sent, in thatorder, by an instance of class A to an instance ofclass B.

One diagram for each system event.

October 2, 2001 Software Design 6

A sequence diagram

message1()

:classAinstance :classBinstance

message2()

message3()

May be used for multiple events.

Focus of control, activation box, optional

October 2, 2001 Software Design 7

Collaboration diagram: makepayment()

:POST :Sale

makePayment(cashTendered) 1: makePayment(cashTendered)

:Payment

1.1: create(cashTendered)

direction of message first internal message

parameter

instance of a classlink line

first message

Note: Post is Register in thesecond edition of Larman.

October 2, 2001 Software Design 8

Making collaboration diagrams

Design a system of interacting objects to fulfill the tasks....this is the tough part of design!

One diagram for each system operation in the current development cycle, e.g. for makepayment().

If the diagram gets complex, split into smaller diagrams.

October 2, 2001 Software Design 9

Classes and Objects

Sale

class

:Sale

object or instance

s1:Sale

named object

October 2, 2001 Software Design 10

Links

:Sale

link line

:Post

msg1()

addPayment(cashTendered)

Link illustrates client/server relationship.

October 2, 2001 Software Design 11

Messages

:Post :Sale

all messages flow on the same link

msg1()

3: message3()2: message2()1: message1()

October 2, 2001 Software Design 12

Parameters

parameters shown within parentheses;types may also be shown

:Post :Sale

msg1()

1: addPayment(amount:Money)

October 2, 2001 Software Design 13

Return values

return value name

:Post :Sale

msg1()

1: tot:=total(): int

return value type

October 2, 2001 Software Design 14

Messages to “self” or “this”

:Post

msg1()

1: clear()

October 2, 2001 Software Design 15

Iteration

:Post :Sale

msg1()

iteration, no recurrence values

1*: li = nextLineItem: SalesLineItem

October 2, 2001 Software Design 16

Iteration with recurrence

msg1()

:Post :Sale

iteration clause

1*: [i:= 1..10] li = nextLineItem: SalesLineItem

October 2, 2001 Software Design 17

Iteration clause: Multiple messages

msg1()

equal iteration clauses

1*: [i:= 1..10] msg2()

:A :myB: B

:myC: C2*: [i:= 1..10] msg3()

msg1(){

for i:= 1 to 10{myB.msg2();myC.meg3();}

}

October 2, 2001 Software Design 18

Creation

:Post :Sale

create message with optional parameter forinitialization. Note that use of the name create is a UML convention.

msg1()

1: create(cashier)

new created instance

<<create>>1: make(cashier)

October 2, 2001 Software Design 19

Languages and create

Language Meaning of create()

C++

Java

Automatic allocation, or new() operator followed by constructor call.

new() operator followed by a constructor call.

October 2, 2001 Software Design 20

Message sequence numbering

:classA :classB

msg1()

first message not numbered

1: msg2()

:classC2: msg4()

second

1.1: msg3()

third (nested)

2.1: msg5()

fourthfifth (nested)

October 2, 2001 Software Design 21

Conditional message

:Post :Sale

msg1()

conditional message with test

1*: [new sale] create()

:SalesLineItem

1.1: create()

October 2, 2001 Software Design 22

Mutually exclusive conditional messages

1a and 1b are mutually exclusive

:ClassA :ClassB

:ClassC:ClassD

:ClassE

msg1() 1a: [test_1] msg2()

1b: [not test_1] msg4() 1a.1: msg3()

1b.1: msg5()

2: msg6()

Unconditional aftereither msg2 or msg4

October 2, 2001 Software Design 23

Collections

sales:Sale

A multiobject or a collection of instances,e.g. a List of Sales.

October 2, 2001 Software Design 24

Messages to Multiobjects

msg1()

1*: s:=size(): int

Message sent to a Multiobject.

:Sale :SalesLineItem*

The two *’s imply iteration over all elements.

October 2, 2001 Software Design 25

Messages to multiobjects and an element [1]

msg1()

1: el:=create()

Message sent to anelement.

:Sale

:SalesLineItem

sl:SalesLineItem

2: addElement(el)

Message sent to acollection.

October 2, 2001 Software Design 26

Design Guidelines

OO system consists of interacting objects.

How does one determine the assignment of responsibilities to various objects?

There is no unique assignment and hence “good” and “poor” designs, “beautiful” and “ugly” designs, “efficient” and “inefficient” designs.

Design guidelines assist in the derivation of a good design.

October 2, 2001 Software Design 27

GRASP Patterns

GRASP: General Responsibility Assignment

Software Patterns

These are best considered as design guidelines and principles. These could also be considered as “thought patterns” useful in software design.

October 2, 2001 Software Design 28

Guidelines and principles

We first consider three useful guidelines:

Expert

and two widely applicable principles: High cohesion Low coupling

Controller

Creator

October 2, 2001 Software Design 29

POS: Partial Domain Model

Sale

datetime

Sales LineItem

quantity

Product Specification

descriptionpriceitemID

Contains

1…*

Store

addressname

POS

CashierCustomerPayment

amount

Manager

Product Catalog

Item

1

Used-by1*

Stocks

*1

Houses1

*

Contained-in1..*

1

Captured-on

11Started-by

11Paid-by 1

11

1Initiated-by

Describes1*

Records-sale-on1

1

October 2, 2001 Software Design 30

Expert

Question: How does one assign responsibilities ?

Answer:Assign a responsibility to an information expert, i.e. to a class that has the information needed to fulfill that responsibility.

October 2, 2001 Software Design 31

Expert: Example [1]

Sale

datetime

Sales LineItem

quantity

Product Specification

descriptionpriceUPC

Contains1…*

Described by*

In POS, some class needs to know the grand total of a sale. Who should be responsible for knowing the grand total of a sale ?

October 2, 2001 Software Design 32

Expert: Example [2]

From the model, identify the class that contains the information needed to obtain the grand total.

Information needed to obtain the grand total: Knowledge of all SaleItems Sum of their subtotals

Only a Sale object possesses this knowledge.

Sale being the information expert, we assign this responsibility to Sale.

October 2, 2001 Software Design 33

Partial collaboration diagram [1]

:Sale1: t:=getTotal()

New method added to the Sale class. The class itself is derived from the domain model.

Sale

datetime

getTotal

October 2, 2001 Software Design 34

Expert: Example [3]

What information is needed to determine subtotal ?

Hence SalesLineItem is assigned the responsibility to compute the subtotal.

We need: Quantity of each SalesLineItem and its price. Quantity is available with SalesLineItem and

price with ProductSpecification.

October 2, 2001 Software Design 35

Partial collaboration diagram [2]

:Sale1: t:=total()

Sale

datetime

getTotal()

SalesLineItem

quantity

getSubtotal()

:ProductSpecification

2.1: p:=getPrice()

ProductSpecification

descriptionpriceitemID

getPrice()

:SalesLineItem

1*: st=getSubtotal()

*

October 2, 2001 Software Design 36

Summary: Example [4]

Class Responsibility

Sale Knows sale total

SalesLineItem Knows line item subtotal.

ProductSpecification Knows the price of a product

October 2, 2001 Software Design 37

Expert: Discussion

Expert guideline used often.

Fulfillment of a responsibility often requires interaction amongst several objects (3 in our example). There are many semi-experts who collaborate in performing a task.

It often leads to “lightweight” classes collaborating to fulfill a responsibility.

Use of the Expert guideline allows us to retain encapsulation of information.

October 2, 2001 Software Design 38

Expert: Disadvantages

On some occasions the Expert guideline might not suggest a desirable solution.

Example: Who should save Sale in a database ?

This implies that the Sale class must know about handling databases. Adding database related methods to sale class will make it in-cohesive.

As all the information to be saved is in the Sale class, it should be responsible for saving the information.

It also violates the “separation of concerns” principle.

October 2, 2001 Software Design 39

Expert: Benefits

Objects use their own information to fulfill tasks, hence encapsulation is maintained.

This leads to low coupling.

Behavior is distributed across cohesive and lightweight classes.

October 2, 2001 Software Design 40

Creator [1]

Question: Who should be responsible for creating an instance of a class ?

Answer:Assign to B the responsibility to create an object of class A if the following is true:

October 2, 2001 Software Design 41

Creator [2]

B aggregates objects of type A.

B contains objects of type A.

B records instances of objects of type A.

B closely uses objects of type A.

B has the data passed to A when A is created.

Implication: B is an expert in the creation of A.

October 2, 2001 Software Design 42

Creator: Example [1]

Sale

datetime

Sales LineItem

quantity

Product Specification

descriptionpriceitemID

Contains1…*

Described by*

Who should be responsiblefor creating a SalesLineItem ?

October 2, 2001 Software Design 43

Creator: Example [2]

Sale contains many SalesLineItem objects.

This leads to the following collaboration diagram.

This implies that Sale is a good candidate for creating a SalesLineItem.

October 2, 2001 Software Design 44

Sequence diagram for the creation of SalesLineItem

:SalesLineItem

makeLineItem(quantity)

create(quantity)

:POST :Sale

October 2, 2001 Software Design 45

Partial collaboration diagram

:Sale makeLineItem(quantity)

Sale

datetime

makeLineItem()total()

:SalesLineItem

New method added to the Sale class.

1: create(quantity)

October 2, 2001 Software Design 46

Creator: Discussion

Creator guides the assignment of responsibility of creating objects.

Creator suggests that the enclosing container or aggregate class is a good candidate for the creation of the object contained.

October 2, 2001 Software Design 47

Controller [1]

Question: Who should be responsible for handling system events ?

Recall that a system event is a high level event, an external event, generated by a system actor.

Answer:Assign a responsibility to handle a system event to a controller.

October 2, 2001 Software Design 48

Controller [2]

A controller is a non-user interface object that handles system events. Here is a list of controllers:

Façade controller: Represents the overall system, device, or business.

Use case controller: Represents an artificial handler of all events of a use case.

October 2, 2001 Software Design 49

Controller [3]

window, applet, view, document do not qualify as controllers. They typically receive system events and delegate them to a controller.

System event examples:

•Pressing the “end of sale” button.

•Request Spell Check.

•Request Engine Start.

October 2, 2001 Software Design 50

System operations

System

endSale()enterItem()makePayment()

During system behavior analysis, system operations are assigned to the class System. It does not imply that the class named System performs these during design. Instead, during design, a controller class is assigned to perform these operations.

October 2, 2001 Software Design 51

Controller: Example (1)

Which object should be responsible for handling the enterItem()system event message ?

enterItem(upc,quantity)

:???

October 2, 2001 Software Design 52

Controller: Example [1]

enterItem(upc,quantity)

:Store

enterItem(upc,quantity)

:Cashier

enterItem(upc,quantity)

:BuyItemsHandler

enterItem(upc,quantity)

:POSTRepresents the overall system

Represents overall business

Represents a real worldactor

Represents an artificialhandler

October 2, 2001 Software Design 53

Controller: Example [2]

System

endSale()enterItem()makePayment()

During design the system operations, identified during analysis, are assigned to one or more of controller classes.

POST

endSale()enterItem()makePayment()

…...

System operationsdiscovered duringanalysis

Allocation of systemoperations during design

October 2, 2001 Software Design 54

Controller: Discussion [1]

Controllers must be chosen to handle incoming events.

Do not assign “too much” responsibility to a controller. A controller should delegate to other objects work that needs to be done while coordinating an activity.

Use the same controller class for events of one use case. This allows maintenance of the state of a use case.

October 2, 2001 Software Design 55

Controller: Discussion [2]

Façade controllers are suitable when there are only a “few” system events.

They are also useful when it is not possible to redirect system events to other controllers as, for example, in a message processing system.

Selecting a use case controller leads to a different controller for each use case. This controller is not a domain object. For example, for “Buy items” use case one might construct a “BuyItemsHandler” class.

October 2, 2001 Software Design 56

Controller: Discussion [3]

When an existing controller becomes too large, one may choose a use case controller. This will likely help in maintaining low coupling and high cohesion.

Corollary: External interfacing objects should not have the responsibility for handling system events. Instead, these should be handled in the domain layer objects as opposed to being handled in application layer objects.

October 2, 2001 Software Design 57

Bloated controller

Signs of a bloated controller: There is only one controller receiving all system

events.

The controller performs all tasks itself without delegating any task to other objects.

A controller has many attributes and maintains significant information about the domain.

A controller duplicates information found in other objects.

October 2, 2001 Software Design 58

Avoiding bloated controller

Add more controllers. If necessary, use role-controllers and use-case controllers.

Role controllers Use case controllers

ReservationAgent

Scheduler

FareAnalyst

MakeAReservationHandler

ManageSchdulesHandler

ManageFaresHandler

An airline reservation system may contain the following controllers:

October 2, 2001 Software Design 59

Presentation (Interface) Layer [1]

Avoid using presentation layer to handle system events.

Example:

Assume that POS application has a window that displays sale information and captures cashier’s operations. Suppose that a Java applet displays the window. Let us see how the presentation and domain layers can be coupled.

Use of domain layer objects to handle system events is preferred.

October 2, 2001 Software Design 60

Object Store

Sample GUI for Point of Sale Terminal

UPC 1

Cash 4

Make Payment10End Sale9Enter Item8

Balance 7

Description 6

Quantity 5

Total 3

Price 2

x_

October 2, 2001 Software Design 61

Sample course of events

Actor System

Customer arrives at thePOST checkout with itemsto purchase.

1

For each item, the Cashierenters the UPC in 1 of Window 1. The quantity of this item is optionally entered in 5.

2 Adds information on the item to the current sales transaction.Description and price of the itemare displayed in 2 and 6 ofWindow 1.

3

October 2, 2001 Software Design 62

Sample course of events(2)

Actor System

Completion of item entry is indicated by the Cashier to POSTby pressing widget 9.

4 Computes and displays thesale total in 3.

5

.......6

October 2, 2001 Software Design 63

Presentation layer [2]

Controller

:SaleJFrame

:POST

1: enterItem(upc,quantity)

:Sale

UPC

Cash

Quantity

Balance

Enter Item End Sale Make Payment

Object Store x_

Cash

onEnterItem()

1.1: makeLineItem(upc,quantity)

System eventmessage

Presses button

Cashier

Presentation layer

Domain layer

October 2, 2001 Software Design 64

Presentation layer [3]

SaleJFrame passes on the enterItem() message to the domain layer.

It does not get involved in the processing of this message.

Thus, business processing logic is in a domain object, not in the presentation object.

Presentation layer objects have lower opportunity for re-use due to their coupling with the environment.

October 2, 2001 Software Design 65

Presentation layer: undesirable coupling [4]

:SaleJFrame

x_

UPC

Cash

Quantity

Balance

Enter Item End Sale Make Payment

Object Store

Cash

onEnterItem()

:Sale

1: makeLineItem(upc,quantity)

Presses button

Cashier

Presentation layer

Domain layer

Business logic embedded inpresentation layer.

October 2, 2001 Software Design 66

Presentation layer [5]

Some applications do not have a user interface. They receive messages from an external system. For example, LDAP (Light Weight Directory Protocol) might receive a message from a CGI script.

In these cases the messages is encoded in a “stream” or as a CORBA message.

October 2, 2001 Software Design 67

Presentation layer [6]

In applications with windows, the window might choose who the controller will be.

Different windows may collaborate with different controllers.

However, in a message handling application, the Command design pattern is useful.

October 2, 2001 Software Design 68

Low coupling

How to achieve low dependency and increased reuse?

A class with high coupling is undesirable because:

• Changes in related classes force local changes.

• This class is harder to understand in isolation.

• This class is harder to reuse because its use requires the inclusion of all classes it is dependent upon.

October 2, 2001 Software Design 69

Low coupling: Example (1)

Payment POST Sale

Consider the following partial conceptual model:

What class should be responsible forcreating an instance of Payment ?

October 2, 2001 Software Design 70

Low coupling: Example [1]

makePayment()

1: create():POST

:Sale

p:Payment

2: addPayment(p)

One solution is to let POST create an instanceof Payment and pass a reference this Payment to Sale. This solution is suggested as POST records a Payment.

October 2, 2001 Software Design 71

Low coupling: Example [3]

makePayment()

1: makePayment():POST :Sale

p:Payment

Another solution is to let Sale create aninstance of Payment.

1.1: create()

Which of the two solutions is preferable from the point of viewof coupling?

October 2, 2001 Software Design 72

Low coupling: Discussion [1]

Encourages assigning a responsibility to keep coupling low.

Supports design of relatively independent, hence more reusable, classes.

Reusable classes have a positive effect on productivity, i.e. may lead to higher productivity.

However, the quest for low coupling to achieve reusability in a future (mythical!) project may lead to increased project cost.

October 2, 2001 Software Design 73

Low coupling: Discussion [2]

It is important for the designer to assess the current level of coupling and attempt to reduce it if it is likely to cause problems.

It is important to note that a moderate degree of coupling between classes is normal. After all an OO application is a collection of communicating objects!

October 2, 2001 Software Design 74

High cohesion

Question: How to keep design complexity manageable.

Answer:Assign responsibilities while maintaining high cohesion.

October 2, 2001 Software Design 75

High cohesion: Example [1]

Creation of a Payment can be assigned to POST as it records a payment in real world. This is suggested by the guidelines associated with Creator.

This is acceptable. However, if this logic is applied in several other similar situations, more and more work is likely to be assigned to one class.

This might lead to an in-cohesive class.

October 2, 2001 Software Design 76

High cohesion: Example [2]

For example, if there are 50 system operations, and POST does some work related to each, the POST will be a large incohesive class.

In contrast, a design that lets Sale create Payment, supports higher cohesion in POST.

This design supports both high cohesion and low coupling and hence is preferred over the first one.

October 2, 2001 Software Design 77

Interaction diagrams and system events

We now consider two use cases and their associated events:

Buy items• enterItem• endSale• makePayment

For each system event we create a collaboration diagram whose starting message is the system event message. What should be our controller class?

Start up• startUp

October 2, 2001 Software Design 78

Choosing the controller class

Choices:POST or a new class such as RetailSystem:

represents the entire system.Store: represents the business.Cashier: represents a real-world entity.BuyItemsHandler: represents an artificial

handler. We select POST as there are only a few system

operations.

October 2, 2001 Software Design 79

Choosing the controller class

1. Choices:

POST or a new class such as RetailSystem: represents the entire system.

Store: represents the business.

Cashier: represents a real-world entity.

BuyItemsHandler: represents an artificial handler.

2. We select POST as there are only a few system operations.

October 2, 2001 Software Design 80

System events

:POST

:POST

:POST

:POST

endSale()

makePayment()

startUp

enterItem()

We select the POST class to handle systemevents.

October 2, 2001 Software Design 81

Interaction diagrams and contracts

For each contract work through the responsibilities and post-conditions, and design message interactions.

Example: The enterItem() system operation requires a Sale to be created in its contract.

A collaboration diagram that satisfies this state change:

October 2, 2001 Software Design 82

Partial collaboration diagram: enterItem()

:POST

enterItem(upc,quantity)

1: [new sale] create()

:Sale

Post-condition: If a new sale, Sale was created (instance creation).

October 2, 2001 Software Design 83

On the value of post-conditions

Post-conditions are only an initial estimate of what must be achieved.

Thus, treat contracts as a starting point for determining what must be done.

New post-conditions might arise during design and old ones might be found redundant.

Recall...we are encouraging iterative development!

October 2, 2001 Software Design 84

Collaboration diagrams and the conceptual model

Some objects in collaboration diagrams are drawn from the conceptual model.

Responsibility assignment depends to some extent upon information in the conceptual model.

New concepts might be discovered during design and previously identified concepts might be ignored.

October 2, 2001 Software Design 85

Collaboration diagram: enterItem (1)

Name: enterItem(upc: number, quantity: int)

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

item description and price.Type: SystemCross reference: Use cases: Buy itemsExceptions: If the UPC is not valid, indicate

that it was an error.

October 2, 2001 Software Design 86

Collaboration diagram: enterItem (2)

Pre-condition:UPC is known to the system.

Post-conditions:

If a new sale, a Sale was created (instance creation)

SalesLineItem.quantity was set to quantity (attribute modification).

If a new sale, Sale was associated with the POST (association formed).

The SalesLineItem was associated with ProductSpecification based on UPC match (association formed).

October 2, 2001 Software Design 87

Collaboration diagram (1)

:POSTenterItem(upc,quantity)

Collaboration diagram begins by “some object” sending an enterItem() message to an instance of POST.

October 2, 2001 Software Design 88

Making a new Sale

Contract post-conditions related to new Sale: If a new Sale, a Sale was created (instance

creation). If a new sale, the new Sale was associated with

the POST (association formed). POST can be considered as one that records Thus,

POST is a reasonable choice as a creator of Sale. POST will then also have a reference to this instance of Sale.

A container SalesLineItem must be created by Sale.

October 2, 2001 Software Design 89

Collaboration diagram

:POSTenterItem(upc,quantity)

Display of the item description and its price is ignored for now.

:Sale1: [new sale] create()

:SalesLineItem

1.1: create()by controller

by creator

an empty collection thatwill eventually hold

instances of SalesLineItem

October 2, 2001 Software Design 90

Creating a new SalesLineItem (1)

More enterItem contract post-conditions: A SalesLineItem was created (instance creation). The SalesLineItem was associated with the Sale

(association formed). SalesLineItem.quantity was set to quantity (attribute

modification) The SalesLineItem was associated with a

ProductSpecification (association formed).

October 2, 2001 Software Design 91

Creating a new SalesLineItem (2)

Sale contains SalesLineItem objects. Hence Sale should create SalesLineItem.

SalesLineItem can be associated with Sale by string it in the container of line items.

POST must pass the quantity to Sale with the create message.

A makeLineItem message is sent to Sale for it to create a SalesLineItem.

October 2, 2001 Software Design 92

Finding a product specification

It is necessary to retrieve ProductSpecification based on the UPC of a SalesLineItem.

Question: Who should have the responsibility for knowing a ProductSpecification ?

Expert guidelines suggest that ProductCatalog is a good candidate for this responsibility.

October 2, 2001 Software Design 93

Visibility to a ProductCatalog

Who should send the specification message to the ProductCatalog to ask for a ProductSpecification ?

We assume that POST and ProductCatalog were instantiated during the StartUp use case and that the are connected permanently.

Thus we let POST send the specification message to ProductCatalog.

Note that POST knows how to get to ProductCatalog. We say that POST has “visibility” to ProductCatalog.

October 2, 2001 Software Design 94

The enterItem() collaboration diagram

:POST

enterItem(upc,qty)

:Sale

1: [new sale] create()

: :SalesLineItem

1.1: create()

by expert :ProductCatalog

2: spec:=specification(upc)

: :SalesLineItem

2.1: spec:=find(upc)

3: makeLineItem(spec,qty)

3.2: add(s))

sl:SalesLineItem

3.1 create(spec,qty)

October 2, 2001 Software Design 95

Collaboration diagram: endSale (1)

Name: endSale()

Responsibilities: Record the end of sale and display sale total.

Type: SystemCross reference: Use cases: Buy itemsExceptions: If a sale is not underway,

indicate that it was an error.

October 2, 2001 Software Design 96

Collaboration diagram: endSale (2)

Pre-condition: UPC is known to the system.

Post-conditions: Sale.isComplete was set to true (attribute modification).

October 2, 2001 Software Design 97

Choosing the controller class

Who should be responsible for receiving the endSale message?

We continue to use POST as the controller.

October 2, 2001 Software Design 98

Setting the Sale.isComplete

Who should be responsible for ensuring the post-condition?

As Sale knows and maintains the isComplete attribute, it should have the responsibility of setting isComplete.

October 2, 2001 Software Design 99

Collaboration diagram: endSale()

:POST

endSale()

:Sale

1: saleComplete()

by controllerby expert

October 2, 2001 Software Design 100

Display of information

One responsibility in the endSale contract is that the sale total must be displayed.

Do not use the domain layer objects to communicate with windows or presentation layer objects.

Use the Observer pattern.Note that Sale must know the total before it

can be displayed!!

October 2, 2001 Software Design 101

Computing the sale total-Review

Who should be responsible form computing the sale total? Obviously…Sale as it is the expert !

What information is required to compute the total ?Sub-totals of all SalesLineItem.

Who should be responsible for computing the sub-totals? Obviously…SalesLineItem as it is the expert in this case.

Who has the price for each SalesLineItem?…ProductSpecification. Hence SalesLineItem must communicate with ProductSpecification to obtain the price.

October 2, 2001 Software Design 102

The Sale total collaboration diagram

:Saletot:=total()

:sli:SalesLineItem

: :SalesLineItem

by expert

2: st:=subtotal()

prodSpec: Productspecification

1*: [for each] sli:=next())2.1: pr=price()

by expert

Sale--total(){ total:=0; for each SalesLineItem.sli

tot:=tot+sli.subtotal();return tot;}

October 2, 2001 Software Design 103

Collaboration diagram: makePayment (1)

Name: makePayment(amount:float)

Responsibilities: Record the payment, compute balance, and print a receipt.

Type: SystemCross reference: Use cases: Buy itemsExceptions: If a sale is not complete,

indicate an error.

October 2, 2001 Software Design 104

Collaboration diagram: makePayment (2)

Pre-condition: None.Post-conditions:

A Payment was created (instance creation) Payment.tendered is set to amount (attribute modification). The Payment was associated with the Sale (relationship

formed). The Sale was associated with the Store to add it to the

historical log of completed sales (relationship formed).

October 2, 2001 Software Design 105

Choosing the controller class

Who should be responsible for receiving the endSale message?

We continue to use POST as the controller.

October 2, 2001 Software Design 106

Creating Payment

Who should be responsible for creating an instance of Payment ?

There are two candidates: POST Sale

Selecting Sale lightens the workload of Payment.

Also POST does not need to know about Payment which leads to lower coupling in POST.

October 2, 2001 Software Design 107

The makePayment collaboration diagram

:POST1: makePayment(cashTendered)

:Sale

by controller

:Payment

1.1create(cashTendered)

by Creator, low coupling

makePayment(cashTendered)

October 2, 2001 Software Design 108

Balance computation collaboration diagram

:Sale1: amt:=amount()

:Paymentbal:=balance()

2 t=total()Sale is responsible for knowing thebalance. It needs visibility intoPayment to ask for cash tendered. AsSale created Payment it has visibility into it.

We have ignored the display of balance.

October 2, 2001 Software Design 109

Logging the Sale (1)

Who should be responsible for knowing all the logged sales and doing the logging ?

There are two candidates: Store SalesLedger (new idea from basic accounting!)

As the design grows Store will become incohesive, hence SalesLedger seems to be a good idea.

October 2, 2001 Software Design 110

Logging the Sale (2)

Consider the following post-condition: The Sale was associated with the Store to add it to the

historical log of completed sales.

This post-condition needs to change if we decide to use SalesLedger to log the sale.

If we decide to use SalesLedger than contracts need to be altered to avoid design divergence.

October 2, 2001 Software Design 111

The logging collaboration diagram

:POST

1: makePayment(cashTendered)s:Sale

by expert

:Payment

1.1create(cashTendered)

makePayment(cashTendered)

:Store

2:addSale(s)

: completedSales:Sale

2.1:add(s)

October 2, 2001 Software Design 112

Collaboration diagram: startUp() (1)

Most systems have a StartUp() use case.It is recommended that the collaboration

diagram for startUp be taken up towards the end.

startUp() operation is often dependent on the programming language and the operating system used.

A common approach is to create an initial domain object.

October 2, 2001 Software Design 113

Collaboration diagram: startUp() (2)

In the initialization method of this initial object, create

other problem domain objects.public class POSTApplet extends Applet { public void init () { post = store.getPOST(); }private Store store = new Store();private POST post;private Sale sale;}

Here, Store is theinitial domain object.It creates other domain objects.

October 2, 2001 Software Design 114

Collaboration diagram: startUp() (3)

Name: startUp()

Responsibilities: Initialize the system

Type: SystemPost-conditions:

Store, POST, ProductCatalog, and ProductSpecifications created (instance creation).

ProductCatalog associated with ProductSpecifications

October 2, 2001 Software Design 115

Collaboration diagram: startUp() (4)

Post-conditions: Store, POST, ProductCatalog, and

ProductSpecifications created (instance creation). ProductCatalog associated with

ProductSpecifications Store associated with POST (association formed). POST associated with ProductCatalog (association

formed).

October 2, 2001 Software Design 116

StartUp collaboration diagram (5)

:Store2: create(pc)

:POST

by creator

ps:productSpecification

create()

pc:ProductCatalog

1:create()

1.1: loadProdSpec

ProductSpecificationProductSpecification

1.1: create()

Reference to the product

catalog passed to POST.

1.2.1*: create(upc,price,description)

1.2.2*: add(ps)

October 2, 2001 Software Design 117

Connecting presentation and domain layers(1)

:POSTApplet store: Storecreate()

First the applet creates an instance of Store. Store in turn creates an instanceof POST. Then the applet requests Store fora reference to the POST instance.The applet can now send messages directly to POST as in the next diagram.

1: create()

2: p=getPOST():POST

October 2, 2001 Software Design 118

Connecting Presentation layer to the domain layer (2)

onEnterItem()

:PostApplet

:POST

UPC

Cash

Quantity

Balance

Enter Item End Sale Make Payment

Object Store x_

Cash

Presses button

Cashier

Domain layer

Presentation layer

1:enterItem(upc,qty)

October 2, 2001 Software Design 119

Connecting Presentation layer to the domain layer (3)

onEnterItem()

:PostApplet

post:POST

UPC

Cash

Quantity

Balance

Enter Item End Sale Make Payment

Object Store x_

Cash

Presses button

Cashier

Domain layer

Presentation layer

1:enterItem(upc,qty)

2: [no sale] sale:=getSale():Sale

sale:Sale

3: t:=total(): float

October 2, 2001 Software Design 120

Class notation

A class

ClassName

methods

attributes

A class diagram exhibits classes and theirassociations used in an application.

Contrast this with a conceptual model which shows domain concepts and their associations.

October 2, 2001 Software Design 121

CRC cards

CRC: Class-responsibility-collaboration cards Instead of using diagrams to show class

responsibilities and collaboration, CRC cards are suggested.

These are index cards and one for each class. In a team, each person plays the role of one

or more classes and holds the corresponding card(s).

Helpful in group design efforts.

October 2, 2001 Software Design 122

CRC cards

Responsibility CollaborationOrder

Check if item in stock

Determine price

Check for valid payment

Dispatch to delivery address

Order line item

Order line item

Customer

Database interface

class name

October 2, 2001 Software Design 123

Summary

What did we learn?

Design process (in part)

Collaboration diagrams (notation)

Creation of collaboration diagrams using design principles and guidelines

Design principles and guidelines

Recommended