ivan marsic rutgers university lecture 7: object oriented design

26
Ivan Marsic Rutgers University LECTURE 7: Object Oriented Design

Upload: whitney-alexander

Post on 18-Dec-2015

225 views

Category:

Documents


2 download

TRANSCRIPT

Ivan MarsicRutgers University

LECTURE 7: Object Oriented Design

2

Topics

• Assigning Responsibilities to Objects• Design Principles

• Expert Doer

• High Cohesion

• Low Coupling

• Business Policies• Class Diagram

3

select function(“unlock")

: SystemUser

«initiating actor»

prompt for the key

enter keyverify key

signal: valid key, lock openopen the lock,turn on the light

Timer«offstage actor»

start ("duration“)

System Sequence Diagrams considered interactions between the actors

We already worked with interaction diagrams: System Sequence Diagrams

System Sequence Diagrams

4

Design: Object Interactions

• System Sequence Diagrams considered interactions between the actors

• Object Sequence Diagrams consider interactions between the objects

checkKey()sk := getNext()

setOpen(true)

: Checker : KeyStorage

val == null : setLit(true)

alt val != null

[else]

Controller : LockCtrl

checkKey()sk := getNext()

setOpen(true)

: Checker : KeyStorage

val == null : setLit(true)

alt val != null

[else]

Controller : LockCtrl

select function(“unlock")

: SystemUser«initiating actor»

prompt for the key

enter keyverify key

signal: valid key, lock openopen the lock,turn on the light

Timer«offstage actor»

start ("duration“)

ystemystem

System Sequence Diagram

DesignSequence Diagram

5

Metaphor for Software Design: “Connecting the Dots”

:Notifier:DatabaseConnDatabaseDatabase LandlordLandlordResidentResident

:Archiver:Controller:SearchRequest:InterfacePage :PageMaker :InvestigRequest

We start with objects/concepts from the Domain Model and modify or introduce new objects, as needed to make the system function work.

6

Types of Object Responsibilities

• Knowing responsibility: Memorizing data or references, such as data values, data collections, or references to other objects, represented as a property

• Doing responsibility: Performing computations, such as data processing, control of physical devices, etc., represented as a method

• Communicating responsibility: Communicating with other objects, represented as message sending (method invocation)

How To “Connect the Dots”

Use Case UC-1: Unlock (flow of events):1. User enters the key code2. System verifies that the key is valid3. System signals the key validity4. System signals: (a) to LockDevice to disarm the lock (b) to LightSwitch to turn the light on

Starting Points: Domain Model from UC-1 (domain concepts):

Q: who handles this data?

Interface objects and Controller

Q: who performs the verification? Based on what data?

Key Checker, based on entered key-code and stored valid keys

message: checkKey(k)

Controller and Interface objects, based on key verification; because they are «boundary»

Q: who signals? Based on what data?

«entity»KeyChecker

«control»Controller

«entity»Key

«entity»KeyStorage

Symbolizes“worker”-typeconcept.

«boundary»KeycodeEntry

«boundary»StatusDisplay

User

Symbolizes“thing”-typeconcept.

Symbolizes“thing”-typeconcept.

LockDevice

LightSwitch

«boundary»HouseholdDeviceOperator

Scenario Walkthrough:for mapping a Use Case scenario to the Domain Model

Controller or Key checker ???, based on key verification

Q: who signals? Based on what data?

return value

message: ???

8

Design: Assigning Responsibilities

(a) (b)

: PageMaker: DatabaseConn

accessList := retrieve(params : string)

interfacePage :=render(accessList : string)

? ?

R1.

R2.

: PageMaker: DatabaseConn

accessList := retrieve(params : string)

interfacePage :=render(accessList : string)

? ?

R1.

R2.

checkKey()

: Checker : DeviceCtrl

?

: Controller

activate( "lock" )

checkKey()

: Checker : DeviceCtrl

?

: Controller

activate( "lock" )

How Data Travels

key-code

Controller Checker Controller LockCtrl

key-code is-valid activation-params

“expert” on key validity

Option A:“expert” (Key Checker) passes the information (key validity) to another object (Controller)which uses it to perform some work (activate the lock device)

key-code

Controller Checker

key-code activation-params

“expert” on key validity

LockCtrl

Option B:“expert” (Key Checker) directly uses the information (key validity)to perform some work (activate the lock device)

Advantage: Shorter communication chain

Drawback: Extra responsibility for Checker

10

Characteristics of Good Designs

• Short communication chains between the objects

• Balanced workload across the objects

• Low degree of connectivity (associations) among the objects

method_1()method_2()…method_N()

method_1()

11

Design Principles

• Expert Doer Principle: that who knows should do the task

• High Cohesion Principle: do not take on too many computation responsibilities

• Low Coupling Principle: do not take on too many communication responsibilities

There are many more …

12

Design: Assigning Responsibilities

(a) (b)

• Although the Checker is the first to acquire the information about the key validity, we decide to assign the responsibility to notify the LockCtrl to the Controller.

• This is because the Controller would need to know this information anyway—to inform the user about the outcome of the key validity checking.

• In this way we maintain the Checker focused on its specialty and avoid assigning too many responsibilities to it.

checkKey()

setOpen(true)

: Checker : DevCtrl

?

: Controller

checkKey()

setOpen(true)

: Checker : DevCtrl

?

: Controller

ok := checkKey()

setOpen(true)

: Checker : DevCtrl: Controller

ok := checkKey()

setOpen(true)

: Checker : DevCtrl: Controller

13

Cohesion

Low cohesion

High cohesion

14

Responsibility-Driven Design

1. Identify the responsibilities• domain modeling provides a starting point

• some will be missed at first and identified in subsequent iterations

2. For each responsibility, identify the alternative assignments– if the choice appears to be unique then move to the next

responsibility

3. Consider the merits and tradeoffs of each alternative by applying the design principles– select what you consider the “optimal” choice

4. Document the process by which you arrived to each responsibility assignment

15

UC-4: View Access Log

: DatabaseConnection: Controller : PageMaker

get( queryRequest : string )

DatabaseDatabase

retrieve records

result

interfacePage := render(accessList : string)

ResidentResident

«html»interfacePage :

specify query

request

accessList := retrieve(params : string)

accessList != NULL

[else]

alt

result displayed

page :=renderList()page :=renderList()

page :=warning()page :=warning()

«post page»

16

Example …

Communicating responsibilities identified for the system function “enter key”:

Responsibility Description

Send message to Key Checker to validate the key entered by the user.

Send message to DeviceCtrl to disarm the lock device.

Send message to DeviceCtrl to switch the light bulb on.

Send message to PhotoObserver to report whether daylight is sensed.

Send message to DeviceCtrl to sound the alarm bell.

17

Unlocking Sequence Diagram

sk = stored key; the process either terminates by matching a stored key or exhausting the key store.Key is a dynamic object, unlike others which are static contains keycode, name, other forms of ID, timestamp, door ID, … -- disposed of after checking

checkKey()sk := getNext()

logTransaction(val)

setOpen(true)

: Controller : Checker : KeyStorage : LockCtrl : Logger: LightCtrl

val == null : setLit(true)

alt val != null

[else]

18

Unlock Use Case

«destroy»

opt

«create»

sk := getNext()

logTransaction( k, val )

activate( "lock" )

: Controller : Checker : KeyStorage : DeviceCtrl : Logger: PhotoObsrv

dl := isDaylight()

alt

[else]

enterKey()

k : Key

val := checkKey( k )loop

activate( "bulb" )

val == true

dl == false

compare(k, sk)

[for all stored keys]

numOfAttempts++

alt numOfAttempts == maxNumOfAttempts

activate( "alarm" )

denyMoreAttempts()

[else]

prompt: "try again"

19

Unlock Seq. Diag. Variation 1

To avoid an impression that the above design is the only one possible!!

Sets a boolean attribute of the Key object: ok = true/false;Business logic (IF-THEN rule) relocated from Controller to LockCtrl

k := create()

sk := getNext()

: Controller : Checker : KeyStorage : LockCtrlk : Key

checkKey(k) loop

setValid(ok)

controlLock(k)

ok := isValid()

opt ok == true

setOpen(true)

k := create()

sk := getNext()

: Controller : Checker : KeyStorage : LockCtrlk : Key

checkKey(k) loop

setValid(ok)

controlLock(k)

ok := isValid()

opt ok == true

setOpen(true)

20

Unlock Seq. Diag. Variations 2&3

Depends on which solution you consider more elegant;It is helpful that checkIfDaylightAndIfNotThenSetLit() is named informatively (reveals the intention), but the knowledge encoded in the name of the method is imparted onto the caller.

: LightCtrl : PhotoSObs

dl := isDaylight()

controlLight()

opt dl == false

setLit(true)

: LightCtrl : PhotoSObs

dl := isDaylight()

controlLight()

opt dl == false

setLit(true)

checkIfDaylightAndIfNotThenSetLit()

: LightCtrl : PhotoSObs

dl := isDaylight()

opt dl == false

setLit(true)

The callercould beController orKeyChecker

checkIfDaylightAndIfNotThenSetLit()

: LightCtrl : PhotoSObs

dl := isDaylight()

opt dl == false

setLit(true)

The callercould beController orKeyChecker

21

Summary of Design Variations

«destroy»

prompt:"try again"

opt

k := create()

sk := getNext()

logTransaction(k, val)

activate(“lock”)

: Controller : Checker : KeyStorage : DeviceCtrl : Logger: PhotoObsrv

dl := isDaylight()

alt

[else]

enterKey()

k : Key

val := checkKey(k)loop

activate(“bulb”)

val == true

dl == false

compare()

[for all stored keys]

numOfTrials++

opt numOfTrials == maxNumOfTrials activate(“alarm”)

: DeviceCtrl : PhotoSObs

dl := isDaylight()

activate( "light" )

opt dl == false

setLit(true)

: DeviceCtrl : PhotoSObs

dl := isDaylight()

activate( "light" )

opt dl == false

setLit(true)

c

a

checkIfDaylightAndIfNotThenSetLit()

: DeviceCtrl : PhotoSObs

dl := isDaylight()

opt dl == false

setLit(true)

The callercould beController orChecker

checkIfDaylightAndIfNotThenSetLit()

: DeviceCtrl : PhotoSObs

dl := isDaylight()

opt dl == false

setLit(true)

The callercould beController orChecker

b

k := create()

sk := getNext()

: Controller : Checker : KeyStorage : DeviceCtrlk : Key

checkKey(k) loop

setValid(ok)

controlLock(k)

ok := isValid()

opt ok == true

setOpen(true)

k := create()

sk := getNext()

: Controller : Checker : KeyStorage : DeviceCtrlk : Key

checkKey(k) loop

setValid(ok)

controlLock(k)

ok := isValid()

opt ok == true

setOpen(true)

Are We Done w/ UC-1: Unlock ?

• Didn’t check that the user is at the right door– Missing: Managing access rights

• Didn’t distinguish critical and non-critical functions– For example, what if logTransaction() call to Logger does not

return, e.g., no access to database (network outage) or disk-space full ?

– Missing: Independent execution of non-critical functions• Adding new household devices causes major

design changes• Business rules are interleaved with authentication

and device management, but business rules are most likely to change

• Etc.

23

Business Policies

IF key ValidKeys THEN disarm lock and turn lights on

ELSE

increment failed-attempts-counter

IF failed-attempts-counter equals maximum number allowed

THEN block further attempts and raise alarm

Should be moved into a separate object:• Make them explicit part of the model• Confine the future changes in business policies

24

Class DiagramBase ClassBase Class

ContainerContainer

KeyChecker

+ checkKey(k : Key) : boolean– compare(k : Key, sk : Key) : boolean

Key

– code_ : string– timestamp_ : long– doorLocation_ : string

KeyStorage

+ getNext() : Key

Logger

+ logTransaction(k : Key)

Controller

# numOfAttemps_ : long# maxNumOfAttempts_ : long

+ enterKey(k : Key)– denyMoreAttempts()

1

1 sensor

logger

11..*

validKeys 1

1 devCtrl

DeviceCtrl

# devStatuses_ : Vector

+ activate(dev : string) : boolean+ deactivate(dev :string) : boolean+ getStatus(dev : string) : Object

PhotoSObsrv

+ isDaylight() : boolean

1

checker

25

Traceability Matrix (3)Mapping: Domain model to Class diagram

Controller-SS1

StatusDisplay

Key

KeyStorage

KeyChecker

HouseholdDeviceOperator

IlluminationDetector

Controller-SS2

SearchRequest

InterfacePage

PageMaker

Archiver

DatabaseConnection

Notifier

InvestigationRequest

Domain Concepts

X

X

X

Con

trol

ler-

SS

2

Sea

rchR

eque

st

«htm

l»in

terf

aceP

age

Pag

eMak

er

Dat

abas

eCon

nect

ion

Con

trol

ler-

SS

1

Key

Key

Sto

rage

Key

Ch

ecke

r

Log

ger

Pho

toS

Obs

rv

Dev

iceC

trl

X

X

X

Software Classes

X

X

X

X

X

X

26

Types of Object Communication

AA BB PPS2S2

S1S1

SNSN

AA BB

(a) (b) (c)