Professional Documents
Culture Documents
Interaction Diagrams
Design Principles
Manuel Medina
CMPS 4131
University of Belize
Dynamic modeling
Interaction Diagrams
Sequence diagrams
Collaboration diagrams
State diagrams
Assigning Responsibilities to Objects
Design Principles
Expert Doer
High Cohesion
Low Coupling
Business Policies
1. Establish
connection Establish Connection
between smart card Establish Connection
and onboard
computer
2. Establish
connection Accept Connection
between onboard
computer and seat
(actually seat Accept Connection
sensor)
newTournament
(league)
:Announce
«new» Tournament
Control
checkMax
Tournament()
setName(name)
setMaxPlayers
(maxp)
commit() create
createTournament Tournament
(name, maxp) «new»
(name, maxp) :Tournament
Tournament
Attributes
Operations
Player Match
* *
Attributes Attributes
Operations Operations
Tournament_
Boundary
Attributes
Operations
Tournament
Announce_
Tournament_ Attributes
Control Operations
Attributes
Operations
Player Match
* *
Attributes Attributes
Operations Operations
newTournament
(league)
:Announce
«new» Tournament
Control
checkMax
Tournament()
setName(name)
setMaxPlayers
(maxp)
commit() create
createTournament Tournament
(name, maxp) «new»
(name, maxp) :Tournament
Tournament_
Boundary
Attributes
Operations
Tournament
Announce_
Tournament_ Attributes
Control Operations
Attributes
createTournament
(name, maxp)
Player Match
* *
Attributes Attributes
Operations Operations
Control
Object
: System
User Timer
«initiating actor» «offstage actor»
select function(“unlock")
enter key
verify key
start ("duration“)
User
«initiating actor»
ystem
: System
Timer
«offstage actor»
checkKey()
sk := getNext()
select function(“unlock")
start ("duration“)
Key Checker, based on entered key-code and stored valid keys message: ???
checkKey()
accessList := retrieve(params : string)
R1.
interfacePage := activate( "lock" )
render(accessList : string) ?
R2.
(a) (b)
Option B:
“expert” (Key Checker) directly uses the information (key validity)
to perform some work (activate the lock device)
Advantage:
key-code key-code activation-params
Shorter communication chain
Controller Checker LockCtrl
Drawback:
Extra responsibility for Checker
“expert” on key validity
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Short communication chains between the
objects
method_1() method_1()
method_2()
…
checkKey() ok := checkKey()
setOpen(true) setOpen(true)
?
(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.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Low cohesion
High cohesion
result
[else] page :=
warning()
Responsibility Description
Send message to Key Checker to validate the key entered by the user.
checkKey()
sk := getNext()
logTransaction(val)
enterKey()
«create»
compare(k, sk)
logTransaction( k, val )
«destroy»
dl := isDaylight()
[else] numOfAttempts++
activate( "alarm" )
[else]
k := create()
checkKey(k) loop
sk := getNext()
setValid(ok)
controlLock(k)
ok := isValid()
opt ok == true
setOpen(true)
To avoid an impression that the above design is the only one possible!!
controlLight() checkIfDaylightAndIfNotThenSetLit()
dl := isDaylight() dl := isDaylight()
compare()
activate( "light" )
logTransaction(k, val) dl := isDaylight()
«destroy»
opt dl == false
dl := isDaylight()
loop
b
checkKey(k) : DeviceCtrl : PhotoSObs
sk := getNext()
setValid(ok)
checkIfDaylightAndIfNotThenSetLit()
controlLock(k) dl := isDaylight()
ok := isValid()
The caller opt dl == false
opt ok == true
could be
Controller or
setOpen(true) Checker setLit(true)
withdraw(50)
getBalance()
setBalance(150)
setBalance(150)
Should BankAccount
be another Thread ?
Final
balance = 150 ??!
:WithdrawCtrl :BankAccount
c1:Customer c2:Customer
withdraw(50)
getBalance()
withdraw(50)
200
computeNewBalance(200,50)
setBalance(150)
End
balance = 100
1
Understand the components of a design
class diagram and how it differs from a
domain model.
Determine which associations are required
to support the messages from the
interaction diagrams.
Know when to use qualified associations.
2
Interaction diagrams are dynamic models
of object-oriented software. They show
in sequence the internal messages
triggered when the façade object
receives a message from an actor.
3
Step 3 of object-oriented program
design specifies precisely the
composition of each message and
the algorithm for each operation in
the program.
4
A qualified association associates two
objects using a qualifier to select objects
at the other end of the association.
FIGURE 9.2
5
Requirements Analysis: The functional model and
the dynamic model deliver operations for the
object model
Object Design: Decide where to put these
operations in the object model
Object design is the process of
adding details to the requirements analysis
making implementation decisions
Thus,
object design serves as the basis of
implementation
The object designer can choose among different ways
to implement the system model obtained during
requirements analysis.
© 2023 Prentice Hall - Slides Modified for CMPS4131
System Problem
Application objects
Requirements gap
Solution objects
Custom objects
Object design gap
Off-the-shelf components
Machine
© 2023 Prentice Hall - Slides Modified for CMPS4131
6
Call the Class
Class User
League Game
1
*
Tournament TicTacToe Chess
7
Requirements analysis activities
Identify attributes and operations without
specifying their types or their parameters
Object design activities
Add visibility information
Add type signature information
Add contracts.
8
There are four ways to obtain visibility in an object-
oriented system:
1. Reference visibility (Navigability): The
client object has a pointer or reference to
the server object.
2. Parameter visibility: An object is provided
by a message as a parameter.
3. Local visibility: An object obtains visibility
to another object by declaring it inside one
of its methods.
4. Global visibility: An object is obtained from
a class by an object requiring visibility to it.
9
Tournament
- maxNumPlayers: int
+ getMaxNumPlayers():int
+ getPlayers(): List
+ acceptPlayer(p:Player)
+ removePlayer(p:Player)
+ isPlayerAccepted(p:Player):boolean
Hashtable
numElements:int
put()
get()
remove()
containsKey()
size()
10
Step 1. Produce an interaction diagram
for each system operation
identified during analysis.
Step 2. Produce a design class diagram
showing the operations from the
interaction diagrams.
Step 3. Specify the signature and the
algorithm for each operation.
11
Produce a design class diagram showing the
operations from the interaction diagrams:
Step 2.1: Identify classes with their behavior.
Step 2.2: Add inheritance to the class diagram.
Step 2.3: Add associations to the class diagram.
Step 2.4: Create a final class diagram with qualified
associations.
12
Identify classes with their behavior.
FIGURE 9.9
(continued)
13
1. Organization (during analysis):
Inheritance helps us with the construction of
taxonomies to deal with the application
domain
when talking the customer and application
domain experts we usually find already existing
taxonomies
2. Reuse (during object design):
Inheritance helps us to reuse models and code
to deal with the solution domain
when talking to developers
14
StartingPoint is always the requirements
analysis phase:
We start with use cases
We identify existing objects (“class
identification“)
We investigate the relationship between these
objects; “Identification of associations“:
general associations
aggregations
inheritance associations.
Car Superclass:
public class Car {
drive() public void drive() {…}
brake() public void brake() {…}
accelerate() public void accelerate() {…}
}
Subclass:
LuxuryCar public class LuxuryCar extends Car
{
public void playMusic() {…}
public void ejectCD() {…}
playMusic()
public void resumeMusic() {…}
ejectCD()
resumeMusic() public void pauseMusic() {…}
pauseMusic() }
15
Inheritance is used in four ways:
Specialization
Generalization
Specification
Inheritance
Implementation Inheritance.
16
First we find the subclass, then the super
class
This type of discovery occurs often in science
and engineering:
Biology: First we find individual animals (Elefant,
Lion, Tiger), then we discover that these animals
have common properties (mammals).
Engineering: What are the common properties of
cars and airplanes?
VendingMachine
Generalization:
The class CoffeeMachine is
discovered first, then the class
SodaMachine, then the
superclass
VendingMachine
CoffeeMachine SodaMachine
totalReceipts totalReceipts
numberOfCups cansOfBeer
coffeeMix cansOfCola
collectMoney() collectMoney()
makeChange() makeChange()
heatWater() chill()
dispenseBeverage() dispenseBeverage()
addSugar()
addCreamer()
© 2023 Prentice Hall - Slides Modified for CMPS4131
17
Called Remodeling if done on VendingMachine
VendingMachine the model level;
called Refactoring if done on totalReceipts
the source code level.
collectMoney()
makeChange()
dispenseBeverage()
CoffeeMachine SodaMachine
totalReceipts totalReceipts
numberOfCups cansOfBeer
coffeeMix cansOfCola
collectMoney() collectMoney() CoffeeMachine
makeChange() makeChange() SodaMachine
heatWater() chill() numberOfCups
coffeeMix cansOfBeer
dispenseBeverage() dispenseBeverage()
addSugar() cansOfCola
heatWater()
addCreamer() addSugar() chill()
addCreamer()
© 2023 Prentice Hall - Slides Modified for CMPS4131
18
Car Airplane
drive() fly()
Airplane Car
fly() drive()
CoffeeMachine
SodaMachine CandyMachine
numberOfCups
coffeeMix cansOfBeer bagsofChips
cansOfCola numberOfCandyBars
heatWater()
addSugar() chill() dispenseSnack()
addCreamer()
© 2023 Prentice Hall - Slides Modified for CMPS4131
19
VendingMaschine
totalReceipts
collectMoney()
makeChange()
dispenseItem()
CoffeeMachine
SodaMachine
numberOfCups CandyMachine
coffeeMix cansOfBeer
cansOfCola bagsofChips
heatWater() numberOfCandyBars
addSugar() chill()
dispenseItem() dispenseItem()
addCreamer()
dispenseItem()
© 2023 Prentice Hall - Slides Modified for CMPS4131
Implementation inheritance
Also called class inheritance
Goal:
Extend an applications’ functionality by reusing
functionality from the super class
Inherit from an existing class with some or all
operations already implemented
Specification Inheritance
Also called subtyping
Goal:
Inherit from a specification
The specification is an abstract class with all
operations specified, but not yet implemented.
© 2023 Prentice Hall - Slides Modified for CMPS4131
20
Implementation Inheritance: The combination of
inheritance and implementation
The Interface of the superclass is completely inherited
Implementations of methods in the superclass
("Reference implementations") are inherited by any
subclass
SpecificationInheritance: The combination of
inheritance and specification
The Interface of the superclass is completely inherited
Implementations of the superclass (if there are any)
are not inherited.
21
Inheritance: Extending a Base class by a new
operation or overwriting an operation.
Delegation: Catching an operation and sending it to
another object.
Which of the following models is better?
List
+Push()
+Pop()
+Top()
© 2023 Prentice Hall - Slides Modified for CMPS4131
22
Code-Reuse can be done by delegation as well as inheritance
Delegation
Flexibility: Any object can be replaced at run time by another
one
Inefficiency: Objects are encapsulated
Inheritance
Straightforward to use
Supported by many programming languages
Easy to implement new functionality
Exposes a subclass to details of its super class
Change in the parent class requires recompilation of the
subclass.
Abstract method:
A method with a signature but without an
implementation (also called abstract operation)
Abstract class:
A class which contains at least one abstract
method is called abstract class
Interface:
An abstract class which has only
abstract methods
An interface is primarily used for the specification of a
system or subsystem. The implementation is provided
by a subclass or by other mechanisms.
23
VendingMachine
dispenseItem() must be
totalReceipts
implemented in each subclass.
collectMoney() We do this by specifying the
makeChange()
dispenseItem()
operation as abstract. Abstract
dispenseItem()
operations are written in UML
in italics.
CoffeeMachine
SodaMachine
numberOfCups CandyMachine
coffeeMix cansOfBeer
cansOfCola bagsofChips
heatWater() numberOfCandyBars
addSugar() chill()
dispenseItem() dispenseItem()
addCreamer()
dispenseItem()
© 2023 Prentice Hall - Slides Modified for CMPS4131
24
Car Superclass:
public class Car {
drive() public final void drive() {…}
brake() public final void brake() {…}
accelerate() public final void accelerate()
{…}
}
Subclass:
LuxuryCar public class LuxuryCar extends Car
{
public void playMusic() {…}
public void ejectCD() {…}
playMusic()
ejectCD() public void resumeMusic() {…}
resumeMusic() public void pauseMusic() {…}
pauseMusic() }
© 2023 Prentice Hall - Slides Modified for CMPS4131
25
Original Java-Code: New Java-Code :
class Device { class Device {
int serialnr; int serialnr;
public final void help() {….} public final void help() {….}
public void setSerialNr(int n) { public void setSerialNr(int n) {
serialnr = n; serialnr = n;
} }
} }
class Valve extends Device {
Position s; class Valve extends Device {
public void on() { Position s;
…. public void on() {
} …
} }
public void setSerialNr(int n) {
serialnr = n + s.serialnr;
}
© 2023 Prentice Hall - Slides Modified for CMPS4131 } // class Valve
Device
Device
- int serialnr
- int serialnr
+void setSerialNr(int n)
+void setSerialnr(int n)
Valve
Valve
-Position s
Position s
+ void on()
+void on()
+ void setSerialNr()
26
class Device {
int serialnr;
public void setSerialNr(int n) {}
}
class Valve extends Device { I expect, that the method
setSerialNr()will be
Position s;
public void on() { overwritten. I only write an
….. empty body
}
public void setSerialNr(int n) {
seriennr = n + s.serialnr;
} Overwriting of the method
} // class Valve setSerialNr() of Class
Device
Example:
Public class SuperClass {
public int add (int a, int b) { return a+b; }
public int subtract (int a, int b) { return a-b; }
}
Public class SubClass extends SuperClass {
public int add (int a, int b) { return a-b; }
public int subtract (int a, int b) { return a+b; }
}
We have redefined addition as subtraction and subtraction
as addition!!
27
Wehave delivered a car with software that allows to
operate an on-board stereo system
A customer wants to have software for a cheap stereo
system to be sold by a discount store chain
Dialog between project manager and developer:
Project Manager:
„Reuse the existing car software. Don‘t change this software, make
sure there are no hidden surprises. There is no additional budget,
deliver tomorrow!“
Developer:
„OK, we can easily create a subclass BoomBox inheriting the
operations from the existing Car software“
„And we overwrite all method implementations from Car that have
nothing to do with playing music with empty bodies!“
© 2023 Prentice Hall - Slides Modified for CMPS4131
Auto BoomBox
engine
windows musicSystem
musicSystem
playMusic()
brake()
ejectCD()
accelerate()
playMusic() resumeMusic()
ejectCD() pauseMusic()
resumeMusic()
pauseMusic() New Abstraction!
© 2023 Prentice Hall - Slides Modified for CMPS4131
28
Auto
BoomBox
engine
windows
musicSystem musicSystem
brake() playMusic()
accelerate()
ejectCD()
playMusic()
ejectCD() resumeMusic()
resumeMusic() pauseMusic()
pauseMusic()
29
Create a FIGURE 9.15
final class
diagram
with
qualified
associations.
SUPPLEMENT READING
30
Carefully define the public interface for classes as well as subsystems
For subsystems use a façade design pattern if possible
Always apply the “Need to know” principle:
Only if somebody needs to access the information, make it publicly
possible
Provide only well defined channels, so you always know the
access
The fewer details a class user has to know
the easier the class can be changed
the less likely they will be affected by any changes in the class
implementation
Trade-off: Information hiding vs. efficiency
Accessing a private attribute might be too slow.
31
There are three common guidelines for assessing
and improving the quality of object-oriented
program design:
Cohesion
Coupling
The Law of Demeter
32
Subclasses are strongly connected to their
superclasses.
.
FIGURE 9.17
33
Cohesion measures how strongly related and focused
the responsibilities of a class are – that is, how
diverse an object’s attributes and behaviors are.
It is desirable to have objects with high cohesion.
Using the Expert pattern helps increase cohesion.
Cohesion refers to how single-minded a module
(class, object, or method) is within a system.
A class or object should represent only one thing, and
a method should solve only a single task.
Three general types of cohesion, method, class, and
generalization/specialization.
Method cohesion addresses the cohesion within an individual
method (i.e., how single minded a method is).
© 2023 Prentice Hall - Slides Modified for CMPS4131
.FIGURE 9.16
34
© 2023 Prentice Hall - Slides Modified for CMPS4131
35
The Law of Demeter states that a client
should give its server the responsibility for
collaborating with other objects.
An object should send messages only to:
Itself
An object to which it contains a reference
A parameter of one of its methods
One of its local objects
A class
Itself (For example, in Figure 9-6a, Object1 can send Message1 to itself. In
other words, a method associated with Object1 can use other methods
associated with Object1.14)
An object that is contained in an attribute of the object or one of its
superclasses (For example in Figure 9-6b, PO1 should be able to send
messages using both its Customer and Date attributes.)
An object that is passed as a parameter to the method (For example in
Figure 9-6c, the aPatient instance sends the message RequestAppt(name,
address) to the aReceptionist instance, which is allowed to send messages
to the instances contained in the name and address parameters.)
An object that is created by the method (For example in Figure 9-6c, the
method RequestAppt associated with the aReceptionist instance creates an
instance of the Appointment class. As such, the RequestAppt method is
allowed to send messages to anAppt.)
An object that is stored in a global variable
36
© 2023 Prentice Hall - Slides Modified for CMPS4131
37
© 2023 Prentice Hall - Slides Modified for CMPS4131
FIGURE 9.18
.
38
Data type is the UML term for the
description of an attribute of a class.
39
A signature is a specification of
an operation which describes
completely the interface of the
operation.
40
Operations are described in the sequence
operation visibility, operation name,
parameter list, and type returned by the
operation:
+ operation name ( in parameter name : parameter type
…,
out parameter name : parameter type … ,
inout parameter name : parameter type , ) : return type
FIGURE 9.23
41
FIGURE 9.25
SUPPLEMENT READING
42
Example of constraints in Arena:
An already registered player cannot be registered
again
The number of players in a tournament should
not be more than maxNumPlayers
One can only remove players that have been
registered
These constraints cannot be modeled in UML
We model them with contracts
Contracts can be written in OCL.
43
An object-oriented contract describes the services
that are provided by an object. For each service, it
specifically describes two things:
The conditions under which the service will be provided
A specification of the result of the service
Examples:
A letter posted before 18:00 will be delivered on the
next working day to any address in Germany
For the price of 4 Euros a letter with a maximum weight
of 80 grams will be delivered anywhere in the USA within
4 hours of pickup.
44
Natural Language
Mathematical Notation
Models and contracts:
A language for the formulation of constraints
with the formal strength of the mathematical
notation and the easiness of natural language:
UML + OCL (Object Constraint Language)
Uses the abstractions of the UML model
OCL is based on predicate calculus
45
A contract is called a formal specification, if
the invariants, rights and obligations in the
contract are unambiguous.
<<precondition>> <<postcondition>>
containsKey(key) !containsKey(key)
46
Many constraints represent domain level
information
Why not use them in requirements analysis?
Constraints increase the precision of requirements
Constraints can yield more questions for the end user
Constraints can clarify the relationships among several
objects
47
Step 2 of object-oriented program design
produces a design class diagram.
This diagram shows the interactions from the
interaction diagrams, visibilities,
and may show qualified associations.
Coupling, cohesion, and the Law of Demeter
are used to refine the diagram.
Defining the signatures and algorithms
for all the operations completes the design
of the business layer.
48
States Machine Diagrams
Manuel Medina
University of Belize
CMPS4131
Domains, Phenomena
States, Events
Context Diagrams
UML State Machine Diagrams
State Activities: Entry, Do, and Exit Activities
Composite States and Nested States
Concurrency
Boolean Logic
UML Object Constraint Language (OCL)
OCL Syntax
OCL Constraints and Contracts
Toy Car Example
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
WORLD
Part/Domain I Part/Domain J
Phenomena in Part i
Phenomena in Part j
Shared
phenomena
Phenomena in Part k
Part/Domain K
PROBLEM DOMAIN
(5) Device
(6) Photosensor preferences
(7) Light
(3) Key
(2) Landlord
(10) Tenant
(9) Desktop computer accounts
(5) Device
(6) Photosensor preferences
(7) Light
Subsystem-2
(3) Key
REQ4
Subsystem-3 (8) Alarm bell (11) Log of
accesses
Software-to-be
(2) Landlord
(10) Tenant
REQ5, REQ7, Subsystem-4 (9) Desktop computer accounts
REQ8, REQ9
(5) Device
(6) Photosensor
preferences
(3) Key
(7) Light
(2) Landlord
(10) Tenant
(9) Desktop computer accounts
(5) Device
(6) Photosensor
preferences
(3) Key
(7) Light
(2) Landlord
(10) Tenant
(9) Desktop computer accounts
(2) Landlord
(10) Tenant
(9) Desktop computer accounts
2 Event: Kick
1
State:
Ball standing 4
Event: Splash
Event: Splash
State:
5 Ball floating
Time
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Set of all pairs of persons
Set of neighbors
Set of sandwiches
Relation:
Sandwich (Bread-slice, Ham-slice, Bread-slice)
DVD player
Power Disc
button tray
… …
Goal:
State1 Event(attr)
Event [condition]/action State2
do/Activity
entry /action Guard
condition
exit/action
Action or
Activity Diagnostics Menu
•User moves cursor to Control Panel or Graph
1.00 1 1.00 1
1.01 2 1.01 2
1.02 3 1.02 3
( prices & number of shares
for all listed stocks )
Event Description
trade Causes transition between stock states Buy, Sell, or Hold
submit Causes transition between trading-order states
InPreparation → OrderPending
matched Causes transition between trading-order states
OrderPending → OrderExecuted
… …
… … 32
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Label Propositions (partial list)
m The action specified by the investor is “buy”
n The investor specified the upper bound of the “buy” price
o The investor specified the lower bound of the “sell” price
event
trade bankruptcy,
merger,
initial-listing acquisition, …
Listing
Traded Delisted
planned
transition
initial state terminal state
indicated by indicated by
composite state
Traded
Listing
Delisted
planned Buy Hold Sell
trade
trade trade
trade trade
Buy Hold Sell
trade trade
trade
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
trade bankruptcy,
acquisition,
initial-listing merger, …
IPO
Traded Delisted
planned
IPO = initial public offering
Traded
bankruptcy,
trade
acquisition,
initial- trade trade merger, …
listing
IPO trade trade
Delisted
planned Buy Hold Sell
trade trade
nested
trade
composite state state
archive view
Pending
submit matched
do: check_price+supply [buy]
InPreparation Executed Archived
check_price+demand [sell]
data cancel,
entry reject
trade Cancelled
“do”
state
activity
invalid-key /
signal-failure invalid-key
[numOfAttemps > maxNumOfAttempts] /
sound-alarm
Locked Accepting
timer-expired /
signal-reset,
set numOfAttemps := 0
autoLockInterval
-expired /
valid-key /
signal-success valid-key / Blocked
signal-success,
set numOfAttemps := 0
Unlocked
Auto-locking feature not shown! Note how the object responds differently to
the same event (invalid-key in Accepting state),
depending on which events preceded it
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
invalid-key [numOfAttemps ≤ maxNumOfAttempts] /
signal-failure
invalid-key /
signal-failure invalid-key
Accepting [numOfAttemps > maxNumOfAttempts] /
sound-alarm
Locked entry: start timer
do: countdown
timer-expired /
signal-reset,
set numOfAttemps := 0
autoLockInterval
-expired /
valid-key /
signal-success
valid-key / Blocked
signal-success
Unlocked
entry: start timer
do: countdown
Vacant arrive /
depart /
Occupied
Occupied
Vacant
Time [days]
A depart
B depart
C arrive
C depart
A arrive
B arrive
Vacant
Time [days]
A depart
B depart
C depart
A arrive
B arrive
C arrive
B make-reservation
Introduce a new object!
Reserved Reserved
by guest B by guest C
Reserved
Object:
Reservation table
Available
reserve
free
Occupied
Object:
Room occupancy
Vacant
current time
Time [days]
A depart
A arrive
Reserved
Object 2:
Reservation table
Available
Occupied
Object 1:
Room occupancy
Vacant
current time
Time [days]
A depart
B depart
C depart
A arrive
B arrive
C arrive
Manuel Medina
CMPS 4131
University of Belize
Subsystem Decomposition
Architectural Styles
1
“
As a software engineer, we need
to have a capability for
choosing/tailoring process
models for a specific project.
“
http://www.newsweek.com/2014/06/06/computer-
programming-dying-art-252618.html
2
IBM Research chief John Kelly likes to say we’re at the dawn of
an era of brain inspired cognitive computers and the beginning
of the end of the 60 year reign of programmable computers that
required us to tell them what to do step by step.
3
A process to transform user requirements into
some suitable form, which helps the
programmer in software coding.
4
Building an abstract representation of reality
Ignoring (insignificant) details.
Focusing on the most important properties.
Level of abstraction depends on viewpoint
and purpose:
Communication
Component interfaces
5
Example: Linux Kernel
16 million Lines of Code!
What does the code do?
Are there dependencies?
Are there different components?
6
Architecture (what is developed?)
High-level view of the overall system:
What components do exist?
…
7
Drawing a picture vs. Programming/Software
Engineering
Let us discuss Similarity vs. Difference
8
Creativity and design
Software development as a c r a f t :
9
product line
product or system architecture decisions
architecture decisions
systemic impact
Product line scope
Subsystem scope
local impact
Class scope
10
Architecture focuses on non-functional
requirements (“cross-cutting concerns”) and
decomposition of functional requirements
11
Our models for systems architecture are based on UML.
For every system, there is a choice of models. Choose
the models that best model the system and are
clearest to everybody.
In UML, every model must have both a diagram and a
supporting specification.
The lectures provide diagrams that give an outline of
the system, without the supporting specifications.
The diagrams shows the relationships among parts of
the system, but much, much more detail is needed to
specify a system.
Problem
Bridge the gap
between a problem and an
existing system in a
manageable way
System
• How? Design
• Use Divide & Conquer:
1) Identify design goals
2) Model the new system
design as a set of
subsystems
3-8) Address the major
design goals. Existing System
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 24
12
System Design
8. Boundary
1. Identify Design Goals Conditions
Additional NFRs Initialization
Trade-offs Termination
Failure.
2. Subsystem Decomposition 7. Software
Layers vs Partitions Control
Coherence & Coupling
Monolithic
Event-Driven
3. Identify Concurrency Conc. Processes
Identification of 4. Hardware/ 5. Persistent Data 6. Global Resource
Parallelism Software Mapping Management Handlung
(Processes, Identification of Nodes Storing Persistent Access Control
Threads) Special Purpose Systems Objects ACL vs Capabilities
Buy vs Build Filesystem vs Database Security
Network Connectivity
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 25
8. Boundary
1. Design Goals Conditions
Definition Initialization
Trade-offs Termination
Failure
2. System Decomposition 7. Software
Layers vs Partitions Control
Coherence/Coupling
Monolithic
Event-Driven
3. Concurrency Conc. Processes
Identification of 4. Hardware/ 5. Data 6. Global Resource
Threads Software Mapping Management Handlung
Special Purpose Systems Persistent Objects Access Control List
Buy vs Build Filesystem vs vs Capabilities
Allocation of Resources Database Security
Connectivity
13
8. Boundary
1. Design Goals Conditions
Nonfunctional
Definition Functional Model
Initialization
Requirements
Trade-offs Termination
Failure
2. System Decomposition 7. Software
Functional Model
Layers vs Partitions Control
Coherence/Coupling
Monolithic
Event-Driven
3. Concurrency Dynamic
Conc. Processes
Identification of 4. Hardware/ 5. Data 6. Global Resource
Model
Dynamic
Threads Software Mapping Management Handlung
Special Purpose Systems
Object Model Access Control List
Model Persistent Objects
Buy vs Build Filesystem vs vs Capabilities
Allocation of Resources Database Security
Connectivity
Nonfunctional Requirements
=> Definition of Design Goals
Functional model
=> Subsystem Decomposition
Object model
=> Hardware/Software Mapping, Persistent Data
Management
Dynamic model
=> Identification of Concurrency, Global Resource
Handling, Software Control
Finally: Hardware/Software Mapping
=> Boundary conditions
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 28
14
Nonfunctional Functional Model
Requirements
8. Boundary
1. Design Goals Conditions
Definition Initialization
Trade-offs Termination
Functional Model Failure
2. System Decomposition Dynamic
Layers vs Partitions Model
Coherence/Coupling 7. Software
Control
Monolithic
Dynamic Object Model Event-Driven
Model Conc. Processes
4. Hardware/ 5. Data
6. Global Resource
3. Concurrency Software Mapping Management
Handlung
Special Purpose Systems Persistent Objects
Identification of Access Control List
Buy vs Build Filesystem vs
Threads vs Capabilities
Allocation of Resources Database
Connectivity Security
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 29
15
Low cost Functionality
Increased productivity User-friendliness
Backward compatibility Usability
Traceability of requirements Runtime Ease of learning
Rapid development Efficiency Fault tolerant
Flexibility Robustness
Reliability
Portability
Client Good documentation
End
(Customer) User
Minimum # of errors
Modifiability, Readability
Reusability, Adaptability
Well-defined interfaces Developer/
Maintainer
Functionality v. Usability
Cost v. Robustness
Efficiency v. Portability
Rapid development v. Functionality
Cost v. Reusability
Backward Compatibility v. Readability
16
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 33
Subsystem
A subsystem is a grouping of elements that form part of a
system.
Coupling is a measure of the dependencies between two
subsystems. If two systems are strongly coupled, it is
hard to modify one without modifying the other.
Cohesion is a measure of dependencies within a
subsystem. If a subsystem contains many closely related
functions its cohesion is high.
An ideal division of a complex system into subsystems has
low coupling between subsystems and high cohesion within
subsystems.
17
Subsystem
The objects and classes from the object model are the
“seeds” for the subsystems
In UML subsystems are modeled as packages
Service
A set of named operations that share a common purpose
The origin (“seed”) for services are the use cases from
the functional model
Services are defined during system design.
18
Components allow systems to be assembled
from binary replaceable elements.
A component is bits not concepts.
A component can be replaced by any other
component(s) that conforms to the interfaces.
A component is part of a system.
A component provides the realization of a set of
interfaces.
19
User Interface
Manages advertisement
banners & sponsorships Manages Administers user
tournaments,promotions, accounts
applications
Tournament
Advertisement User Management
Tournament
Session Statistics
Management Stores user profiles
Stores results of
Maintains state (contact info &
archived
during matches subscriptions)
tournaments
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 39
20
A package is a general-purpose mechanism for organizing
elements into groups.
21
Good design: The subsystem interface object
describes all the services of the subsystem
interface
22
A layer is a subsystem that provides a service to
another subsystem with the following restrictions:
A layer only depends on services from lower layers
A layer has no knowledge of higher layers
A layer can be divided horizontally into several
independent subsystems called partitions
Partitions provide services to other partitions on the
same layer
Partitions are also called “weakly coupled” subsystems.
Can the client and server layers run on the same machine?
UML convention:
Runtime dependencies are associations with dashed lines
Compile time dependencies are associations with solid lines.
23
Partition Layer
relationship Relationship
A:Subsystem „depends on“ Layer 1
User Interface
Tournament
Advertisement User Management
Component
Management
User Directory
Tournament
Session Statistics
Management
24
User Interface
Component
Management
Advertisement Tournament
Tournament
Statistics
25
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 51
26
√
(a) Projection - Projection just simplifies the representation (b) Partition - isolates the parts from one
(by removing some dimensions), while preserving another—it simplifies by
the relationships between the parts. removing the relationships.
REQ1, REQ2,
REQ3 REQ3, REQ4
PROBLEM DOMAIN
(5) Device
(6) Photosensor
preferences
(7) Light
Subsystem-2
(3) Key
REQ4
Subsystem-3 (8) Alarm bell (11) Log of
accesses
Software-to-be
(2) Landlord
(10) Tenant
Subsystem-4 (9) Desktop computer accounts
REQ5, REQ7,
REQ8, REQ9
Subsystems derived from the requirements
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 54
27
1. User works with computer system 1.a) System transforms input document to output document
(environment irrelevant/ignored)
Repository
User
System Environment
3. Computer system intermediates between 3.a) System observes the environment and displays information
the user and the environment
User System Environment 3.b) System controls the environment as commanded by the user
28
SUPPLEMENT
Abstraction
Stepwise refinement: decomposition
Modularity Modularization
Information hiding
Top-down versus Bottom-up
Cohesion, coupling
29
Modularization is a technique to divide a
software system into multiple discrete and
independent modules, which are expected to be
capable of carrying out task(s) independently.
These modules may work as basic
constructs(building block) for the entire
software.
30
Encapsulation means drawing a boundary around
something. It means being able to talk about the
inside and the outside of it. Object-oriented
languages provide a way to do this.
Information hiding is the idea that a design
decision should be hidden from the rest of the
system to prevent unintended coupling.
Encapsulation is a programming language feature.
Information hiding is a design principle.
(source: wiki)
Functional independence
Based on the concepts of abstraction and
information hiding.
Each module has
a specific functionality of requirements
a simple interface when viewed from outside.
Measured by two qualitative criteria:
cohesion
coupling
31
The measure of strength of the association of elements
within a module.
Modules whose elements are strongly and genuinely related
to each other are desired.
Levels of cohesion
Coincidental
Logical
Temporal
Procedural
Communicational better quality
Informational
Functional
32
Logical Cohesion Procedural Cohesion
The elements in a module perform The elements in a module are
similar or related functions that fall into involved in different activities, but are
the same logical class. invoked as a sequence.
Examples: Examples:
InputAll, OutputAll. Calculate_Trajectoryand Activate_Alarms;
Read part_numberfrom DB and Update
General error handling.
repair_recordon maintenance_file;
Temporal Cohesion Communicational Cohesion
All the elements in the module are All of the elements in a module
activated at a single time. operates on the same input data or
Examples: produce the same output data.
Initialization Examples:
Termination Calculate new trajectory and send it to
printer;
Update record in DB and write it to audit
file;
33
A module performs exactly one action or achieves a single goal.
Improve reusability.
Ease to maintain.
Ease to extend.
Examples:
Get temperature of furnace.
Compute orbital of electron.
Calculate sales commission.
34
The measure of the interdependence of one module to
another.
Low coupling minimize ripple effect.
Levels of coupling
Content
Common
Control better quality
Stamp
Data
Content Coupling
One module branches into another module.
One module references or alters data contained inside another module.
Examples:
Module P modifies a statement of module Q.
Module P refers to local data of module Q.
Module P branches to a local label of Module Q
Common Coupling
Two modules share the same global variables
Example: ‘common’ in Fortran
Drawbacks:
Reduce readability.
Can introduce side effects.
Difficult to maintain.
Difficult to reuse.
May cause security problems.
35
Control Coupling
Two modules communicate through control flags.
One module explicitly controls the logic of the other.
Q: control-coupled?
“Module P calls module Q, and passes back a flag to P that says, "I am unable to
complete my task.", then Q is passing data.''
If the flag means, "I am unable to complete my task; accordingly, write error message
ABC123.” control coupled
Drawbacks:
Two modules are not independent.
Generally associated with logical cohesion.
Stamp Coupling
Two modules communicate via a passed data structure which contains more information
than necessary.
Example:
Calculate_withholding(employee_record).
Drawbacks:
Difficult to understand the interface.
Difficult to reuse.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 71
Data Coupling
Two modules communicate via parameters.
Should be a goal of design.
Easy to maintain
Examples:
Display_time_of_arrival (flight_number).
Compute_product(first_number, second_number, result).
36
Management Aspects
Preliminary design: transformation of
requirements into data and software
architecture.
Technical Aspects
Datadesign: transformation of the information domain
model created during analysis into the data structures.
37
Select/Design data representation
Concept of persistency
Operation(behavior) > Data
Operation = Data
Operation < Data
Goal:
To develop a modular program structure.
To represent the control relationships between modules.
Also, melds program structure and data structures, defining interfaces.
A story:
You've saved money, purchased a beautiful piece of land, and have decided to
build a house of your dreams. Having no experience in such matters, you visited a
builder and explain your desire[e.g., size and number of rooms, etc. The builder
listens carefully, asks a few questions, and then tells you that he'll have a design in
a few weeks. As you wait anxiously for his call, you come up with many different
images of your new house. What will he come up with? Finally, the phone rings
and you rush to his office. Pulling out a large folder, the builder spreads a
diagram of the plumbing for the second floor bathroom in front of you and
proceeds to explain it in detail. "But what about the overall design!" you say.
"Don't worry,'' says the builder,
"We will get to that later."'
38
Define algorithmic details.
sequence, control, repetition.
Notations:
Graphical design notation
Flowcharts,
Nassi-Shneidermancharts
Pseudocode
39
Reusable patterns commonly occurring in SW
architectural design phase.
Most widely used architectural patterns
Layered
Client-server
Pipe-filter
Broker
Event-bus
MVC
MVVM
MVP
1. Components
Processing elements that “do the work”
2. Connectors
Enable communication among components
Broadcast Bus, Middleware-enabled, implicit (events), explicit
(procedure calls, ORBs, explicit communications bus) …
3. Interfaces
Connection points on components and connectors
define where data may flow in and out of the
components/connectors
4. Configurations
Arrangements of components and connectors that form an
architecture
40
a.k.a. Tiered Software Architecture
Agility
Ease of development
Performance
Ease of deployment
Suitable for Devops
41
The server component listens client requests, provides services
to multiple client component
Server does not need to know clients
Online applications such as email,
banking, etc
42
Structure a system which produces and processes a stream of data.
Each processing unit is enclosed within a filter component
Data to be processed is passed through pipes
Components: Filters transform input into output
Connectors: Pipe data streams
Example: UNIX shell commands
Compiler, workflow machine,.. IoT, Digital Twins, CPS,..
B,CMPS4131,Joe
B,CMPS3141,Joe 2A
A,CMPS4131,Ben
A,CMPS4131,Tadeo ???? 1B
43
B,CMPS4131,Joe
B,CMPS3141,Joe 2A
A,CMPS4131,Ben 1B
grep CMPS4131 grades.csv | cut –f1 –d ‘,’ | sort | uniq -c
A,CMPS4131,Tadeo
B,CMPS4131,Joe B
B,CMPS4131,Joe 2A
B,CMPS3141,Joe A
A,CMPS4131,Ben 1B
A,CMPS4131,Ben A
A,CMPS4131,Tadeo
A,CMPS4131,Tadeo
B,CMPS4131,Joe
B,CMPS3141,Joe 2A
A,CMPS4131,Ben grep CMPS4131 grades.csv | cut –f1 –d ‘,’ | sort | uniq -c 1B
A,CMPS4131,Tadeo
44
Structure a distributed system with decoupled components.
Broker component is responsible for the coordination and
communication among components
Servers publish their capabilities to a broker
Clients request a service from the broker, and the broker
redirects the client to a suitable service.
Message broker:
Apache Active MQ,
JbossMessaging
Has 4 components
Event source: publish messages to particular channels
Event listener: subscribe to particular channels, are notified of
messages
Channel
Event bus
Common API
Android development
45
Model: holds all the data, state and application logic.
Oblivious to the View and Controller. Provides API to
retrieve state and send notifications of state changes to
“observer”
View: gives you a presentation of the Model. Gets data
directly from the Model
Controller: Takes user input and figures out what it
means to the Model
display
5. I need your state (to display)
View
4. I have changed
input device
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 91
User Interface
Model
Controller
Input Domain
Event Domain
device model
Interpreter Model
events action
Notification
Visual feedback
Model about the
User of the altered
Visualizer effects of the
model
action
31
26 14
14 31
versus
Different Views for the same Model: 26
46
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 93
47
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 95
48
STRUCTURAL MODELING
-Structural Models
-Domain Model
-Class Diagram
-System Contracts
Manuel Medina
CMPS 4131
University of Belize
Domain Modeling
Identifying Classes/Concepts
Class/Concept Attributes
Class/Concept Associations
Class Diagram(First Pass)
Object Diagram (First Pass)
Domain Model
Safe House Example
Contracts: Preconditions and Postconditions
1
• Understand the rules and style guidelines for
creating CRC cards, class diagrams, and
object diagrams.
• Understand the processes used to create CRC
cards, class diagrams, and object diagrams.
• Be able to create CRC cards, class diagrams,
and object diagrams.
• Understand the relationship among structural
models.
• Understand the relationship between
structural and functional models.
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 3
2
Drawn using an iterative process
First drawn in a conceptual, business-centric way
Then refined in a technology-centric way
describing the actual databases and files
More and more detail is added in each iteration
Create a vocabulary for analysts & users
Allows effective communication between
analysts & users
Structural
Modeling
Solution Domain
Problem Domain
3
Step 1. Identify the business events and make
an event table.
Step 2. Identify the use cases and produce a
use case diagram for the system.
Step 3. Write a use case narrative describing
the system’s response to each
business event.
4
Produce a domain model showing the
concepts, attributes, and associations
in the problem domain of the system.
5
Use Domain Models to help design everything
from small applications to huge databases and
enterprise architecture.
The model contains a graphical representation of
the entities in your application's domain, as well
as the associations between them.
Domain models can be thought of as a superset
of Entity Relational Diagrams for database design
and UML Class Diagrams for object-oriented
design.
6
Captures the most important types of objects in a
system.
Describing “things” in a system and how these
things are related to each other.
A “thing” can be an object, a class, an interface, a
package or a subsystem, which is part of the system
being developed.
Very important process because it is employed
throughout the entire system development life
cycle.
7
.
8
Main goal: Find the important abstractions
Steps during object modeling
1. Class identification (concepts)
Based on the fundamental assumption that we can find abstractions
2. Find the attributes
3. Find the methods
4. Find the associations between classes
Order of steps
Goal: get the desired abstractions
Order of steps secondary, only a heuristic
What happens if we find the wrong abstractions?
We iterate and revise the model
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 17
9
Class identification is crucial to object-oriented
modeling
Helps to identify the important entities of a system
Basic assumptions:
1. We can find the classes for a new software system
(Forward Engineering)
2. We can identify the classes in an existing system
(Reverse Engineering)
Why can we do this?
Philosophy, science, experimental evidence.
10
Step 2. Modify the set of classes
Goals:
Improve the clarity of the design
If the purpose of each class is clear, with easily
understood methods and relationships, developers
are likely to write simple code, which future
maintainers can understand and modify.
Increase coherence within classes, and lower coupling
between classes.
Aim for high cohesion within classes and weak
coupling between them.
11
One problem: Definition of the system boundary:
Which abstractions are outside, which abstractions are
inside the system boundary?
Actors are outside the system
Classes/Objects are inside the system.
An other problem: Classes/Objects are not just
found by taking a picture of a scene or domain
The application domain has to be analyzed
Depending on the purpose of the system different
objects might be found
How can we identify the purpose of a system?
Scenarios and use cases => Functional model
Entity Objects
Represent the persistent information tracked by
the system (Application domain objects, also
called “Business objects”)
Boundary Objects
Represent the interaction between the user and
the system
Control Objects
Represent the control tasks performed by the
system.
12
To distinguish different object types
in a model we can use the
UML Stereotype mechanism
Year Button
ChangeDate
Month
LCDDisplay
Day
<<Entity>> <<Boundary>>
Year Button
<<Control>>
<<Entity>> ChangeDate
Month
<<Boundary>>
<<Entity>> LCDDisplay
Day
Entity Object Control Object Boundary Object
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 26
13
Stereotypes allow you to extend the vocabulary of
the UML so that you can create new model
elements, derived from existing ones
Examples:
Stereotypes can also be used to classify method behavior
such as <<constructor>>, <<getter>> or <<setter>>
To indicate the interface of a subsystem or system, one
can use the stereotype <<interface>> (Lecture System
Design)
Stereotypes can be represented with icons and
graphics:
This can increase the readability of UML diagrams.
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 27
14
Library Example
Student Registration Example
15
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 31
16
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 33
17
Methods used to move to final design
Reuse: Wherever possible use existing components, or class libraries. They may
need extensions.
Restructuring: Change the design to improve understandability, maintainability,
etc. Techniques include merging similar classes, splitting complex classes, etc.
Optimization: Ensure that the system meets anticipated performance
requirements, e.g., by changed algorithms or restructuring.
Completion: Fill all gaps, specify interfaces, etc.
Design is iterative
As the process moves from preliminary design to specification, implementation,
and testing it is common to find weaknesses in the program design. Be prepared
to make major modifications.
Concepts (Objects)
18
Attributes describe concepts.
19
An instance of a concept is a specific
occurrence of a concept type.
Student Student
Student Concept: Instance 1: Instance 2:
Attributes Values Values
studentIdentifier 40168 82704
major CIS CS
classLevel Junior Sophomore
FIGURE 5.7
20
Always model associations explicitly;
never use an attribute to imply an
association.
21
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 43
22
Picka use case and look at flow of events
Do a textual analysis (noun-verb analysis)
Nouns are candidates for objects/classes
Verbs are candidates for operations
This is also called Abbott’s Technique
After objects/classes are found, identify their types
Identify real world entities that the system needs to keep
track of (FieldOfficer Entity Object)
Identify real world procedures that the system needs to keep
track of (EmergencyPlan Control Object)
Identify interface artifacts (PoliceStation Boundary
Object).
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 45
23
Common Object Lists
Physical things
Incidents
Roles
Interactions
Patterns
Useful groupings of collaborating classes that
provide solutions to common problems (are
reusable)
Developed patterns provide a starting point for
work in similar domains
Flow of Events:
The customer enters the store to buy a toy.
It has to be a toy that his daughter likes
and it must cost less than 50 Euro.
He tries a videogame, which uses a data
glove and a head-mounted display. He likes
it.
An assistant helps him.
The suitability of the game depends on the
age of the child.
His daughter is only 3 years old.
The assistant recommends another type of
toy, namely the boardgame “Monopoly".
24
Example Part of speech UML model component
“Monopoly” Proper noun object
Toy Improper noun class
Buy, recommend Doing verb operation
is-a being verb inheritance
has an having verb aggregation
must be modal verb constraint
dangerous adjective attribute
enter transitive verb operation
depends on intransitive verb Constraint, class,
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131
association
49
25
Syntactical investigation with Abbot‘s technique:
Flow of events in use cases
Problem statement
26
Purpose of class diagrams
The description of the static properties of a
system
The main users of class diagrams:
The application domain expert
uses class diagrams to model the application domain
(including taxonomies)
during requirements elicitation and analysis
The developer
uses class diagrams during the development of a
system
during analysis, system design, object design and
implementation.
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 53
27
UML Notation
28
A class is a description of a set of objects that share the same attributes,
methods, relationships, and semantics.
Note on terminology. This course uses the term methods for the
operations that a class supports. UML uses the less familiar term
operations for this purpose.
29
Describe how classes relate to one another
30
Note that the Applet and
Graphics classes are shown
elided, i.e., just the name
is shown, not the
attributes or operations.
Properties of a class
Person: last name, first name, address, etc.
Attributes can be derived
Preceded with a slash (/)
e.g., age is derived from date of birth
Visibility of an attribute:
Restricts access to attributes to ensure consistency
Public attributes (+): visible to all classes
Private attributes (-): visible only to an instance of the
class in which they are defined
Protected attributes (#): visible only to an instance of
the class in which they are defined and its descendants
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 62
31
Common operations are not shown
Create or delete an instance
Return or set a value
Types of operations:
Constructor—creates an object
Query—makes information about the state of an
object available
Update—changes values of some or all of an
object’s attributes
Destructor—deletes or removes an object
32
Department Boss Exactly one:
1 1 A department
has one and
only one boss
Employee Child Zero or more:
1 0..* An employee
has zero to
many children
Boss Employee One or more:
1 1..* A boss is
responsible for
one or more
employees
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 65
33
Generalization denotes inheritance
Properties and operations of the superclass are
valid for the sub-class
Depicted as a solid line with a hollow arrow
pointing at the superclass
Aggregation denotes a logical “a-part-of”
relationship
Composition denotes a physical “a-part-of”
relationship
34
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 69
35
Fullypopulated class diagrams of real-world
system can be difficult to understand
Common ways of simplifying class diagrams:
Show only concrete classes
The view mechanism shows a subset of classes
Packages show aggregations of classes (or any
elements in UML)
36
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 73
37
5. Attributes on the back of the CRC card each
have a data type (e.g., salary implies a
number format)
6. Relationships on the back of the card must
be properly depicted on the class diagram
a) Aggregation/Association
b) Multiplicity
7. Association classes are used only to include
attributes that describe a relationship
Supplement Example
38
In use case analysis, we consider In domain analysis, we consider
the system as a “black box” the system as a “transparent box”
(a) (b)
System Domain Model
Use Case 1
Use Case 2
Actor
Actor
Use Case N Actors
Actors
System
(b)
4
1
2 Domain Model
7 5 3
8 6
0 9
Actor Concept 3
(Bank
Actor
(AT Concept 1
customer) M (Remote
ma datacenter)
chi
ne)
(a) Concept n
Actor Concept 2
Actor
39
Step 1: Identifying the boundary concepts
Internal
Concept 2 concepts
Concept 4
Actor B Actor D
Related Requirements: REQ1, REQ3, REQ4, and REQ5 stated in Table 2-1
Actor’s Goal: To disarm the lock and enter, and get space lighted up automatically.
1. Tenant/Landlord arrives at the door and selects the menu item “Unlock”
2. include::AuthenticateUser (UC-7)
System (a) signals to the Tenant/Landlord the lock status, e.g., “disarmed,” (b) signals to
3.
LockDevice to disarm the lock, and (c) signals to LightSwitch to turn the light on
4. System signals to the Timer to start the auto-lock timer countdown
5. Tenant/Landlord opens the door, enters the home [and shuts the door and locks]
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 80
40
Responsibility Description Type Concept Name
Coordinate actions of all concepts associated with a use case, a logical grouping of use cases,
D Controller
or the entire system and delegate the work to other concepts.
Container for user’s authentication data, such as pass-code, timestamp, door identification, etc. K Key
Verify whether or not the key-code entered by the user is valid. D KeyChecker
Container for the collection of valid keys associated with doors and users. K KeyStorage
Block the input to deny more attempts if too many unsuccessful attempts. D Controller
Symbolizes Symbolizes
“worker”-type “thing”-type
concept. concept. «entity»
«entity»
KeyChecker KeyStorage
«boundary» «entity»
KeycodeEntry Key
«boundary» «control»
StatusDisplay Controller LockDevice
«boundary»
HouseholdDeviceOperator
Resident LightSwitch
41
«boundary»
HouseholdDeviceOperator
Associations: who needs to work together, not how they work together
Domain model for UC-1: Unlock Concept pair | Association description | Association name
verifies
conveys requests
«entity»
obtains Attributes
Key
«boundary»
KeycodeEntry userIdentityCode
timestamp
doorLocation
Association
«boundary» name
StatusDisplay
«control» LockDevice
Controller conveys requests «boundary»
HouseholdDeviceOperator
numOfAttempts
maxNumOfAttempts deviceStatuses
42
«boundary»
HouseholdDeviceOperator
deviceStatus
Preconditions: Tenant/Landlord is currently logged in the system and is shown a hyperlink “View Access History.”
Postconditions: None.
2. System prompts for the search criteria (e.g., time frame, door location, actor role, event type, etc.) or “Show all”
43
Responsibility Description Type Concept Name
Rs1. Coordinate actions of concepts associated with this use case and delegate the work to
D Controller
other concepts.
Rs2. Form specifying the search parameters for database log retrieval (from UC-5, Step 2). K Search Request
Rs3. Render the retrieved records into an HTML document for sending to actor’s Web browser
D Page Maker
for display.
Rs4. HTML document that shows the actor the current context, what actions can be done, and
K Interface Page
outcomes of the previous actions.
Rs5. Prepare a database query that best matches the actor’s search criteria and retrieve the
D Database Connection
records from the database (from UC-5, Step 4).
Rs6. Filter the retrieved records to match the actor’s search criteria (from UC-5, Step 6). D Postprocessor
Rs7. List of “interesting” records for further investigation, complaint description, and the
K Investigation Request
tracking number.
Rs8. Archive the request in the database and assign it a tracking number (from UC-5, Step 8). D Archiver
Rs9. Notify Landlord about the request (from UC-5, Step 8). D Notifier
Page Maker Database Database Connection passes the retrieved data to Page Maker to
provides data
Connection render them for display
Page Maker Interface
Page Maker prepares the Interface Page prepares
Page
Controller Database
Controller passes search requests to Database Connection conveys requests
Connection
Archiver Investigation
Archiver generates Investigation Request generates
Request
Associations (describe who needs to work together and why, not how they work together).
44
Concept Attributes Attribute Description
Used to determine the actor’s credentials, which in turn specify what kind of
user’s identity
data this actor is authorized to view.
Search
Request
Time frame, actor role, door location, event type (unlock, lock, power failure,
search parameters
etc.).
Copied from search request; needed to Filter the retrieved records to match
Postprocessor search parameters
the actor’s search criteria.
Archiver current tracking number Needed to assign a tracking number to complaints and requests.
Contact information of the Landlord who accepts complaints and requests for
Notifier contact information
further investigation.
posts «boundary»
Notifier
«boundary»
InterfacePage saves-data-to
contactInfo
Landlord
conveys-requests
prepares
«entity» «boundary»
PageMaker DatabaseConnection
provides-data
Resident Database
45
Professional user
Speaks Esperanto
Conformity-driven Potential user
Expected commands: Speaks Klingon
Ekzemplero, Alglui, Curiosity-driven
Redakti, Viŝi Expected commands:
nIH, Suq, naw‘, Degh
CURRENT USER
C Accidental user
Does not speak
Chance-driven
Expected commands:
<meaningless - ignore>
REQ1 5 X X
REQ2 2 X
REQ3 5 X X
REQ4 4 X X
REQ5 2 X X
REQ6 1 X X X
REQ7 2 X X
REQ8 1 X X
REQ9 1 X X
Max PW 55 52 12 21 11 2
5 25 12
Total PW 16
15 93 1
2 21 32 92 29 35
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 92
46
UC1: Unlock
Mapping: Use cases to Domain model UC2: Lock
UC3: AddUser
UC4: RemoveUser
UC5: InspectAccessHistory
Domain Concepts UC6: SetDevicePrefs
UC7: AuthenticateUser
UC8: Login
HouseholdDeviceOperator
DatabaseConnection
InvestigationRequest
SearchRequest
Controller-SS2
Controller-SS1
InterfacePage
KeycodeEntry
StatusDisplay
KeyChecker
KeyStorage
PageMaker
Archiver
Notifier
Use Key
PW
Case
16
UC1 15 X X X X X
UC2 3
9
X X X
UC3 2
1
X X X X
UC4 2
1 X X X X
UC5 3
2 X X X X X X X X
UC6 9
2 X X X X
UC7 2
9 X X X X X
UC8 3
5
X X X X
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 93
47
Write a contract for each system operation.
48
A contract formalizes the interactions between the
client and server objects.
For example, a patient makes an appointment with a
doctor. This sets up an obligation for both the patient
and doctor to appear at the appointed time.
Otherwise, consequences, such as billing the patient for
the appointment regardless of whether he or she
appears, can be dealt out.
Also, the contract should spell out what the benefits of
the contract will be, such as a treatment being
prescribed for whatever ails the patient and a payment
to the doctor for the services provided.
49
Identify each system operation
in a system sequence diagram.
Write the responsibilities of that operation
in the contract.
Write the preconditions in terms of
the required changes in the domain model.
Add the postconditions and exceptions.
50
FIGURE 5.28
FIGURE 5.27
51
Operation Unlock
• set of valid keys known to the system is not empty
• numOfAttempts maxNumOfAttempts
Preconditions
• numOfAttempts = 0, for the first attempt of the current user
Operation Lock
Preconditions
None (that is, none worth mentioning)
Design
System Sequence Diagram Sequence Diagram
User
«initiating actor»
ystem
: System
Timer
«offstage actor»
checkKey()
sk := getNext()
select function(“unlock")
start ("duration“)
52