You are on page 1of 260

DYNAMIC MODELING (CONT)

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Two UML diagrams types for dynamic modeling:
 Interaction diagrams describe the dynamic behavior
between objects
 Statechart diagrams describe the dynamic behavior
of a single object.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Two types of interaction diagrams:
 Sequence Diagram:
 Describes the dynamic behavior of several objects over
time
 Good for real-time specifications
 Collaboration Diagram:
 Shows the temporal relationship among objects
 Position of objects is based on the position of the
classes in the UML class diagram.
 Does not show time,

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 State Chart Diagram:
 A state machine that describes the response of
an object of a given class to the receipt of
outside stimuli (Events).
 Activity Diagram:
 A special type of state chart diagram, where all
states are action states (Moore Automaton).

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Definition of a dynamic model:
 Describes the components of the system that have
interesting dynamic behavior
 The dynamic model is described with
 State diagrams: One state diagram for each class
with interesting dynamic behavior
 Classes without interesting dynamic behavior are not
modeled with state diagrams
 Sequence diagrams: For the interaction between
classes
 Purpose:
 Detect and supply operations for the object model.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
A sequence diagram is a graphical description
of the objects participating in a use case
using a DAG notation
 Heuristic for finding participating objects:
 A event always has a sender and a receiver
 Find them for each event => These are the
objects participating in the use case.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Flow of events in “Get SeatPosition” use case :

1. Establish connection between smart card and onboard


computer

2. Establish connection between onboard computer and


sensor for seat

3. Get current seat position and store on smart card

 Where are the objects?

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Smart Card Onboard Computer Seat

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)

3. Get current seat Get SeatPosition


position and store
on smart card. “500,575,300”
time

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


• Layout:
1st column: Should be the actor of the use case
2nd column: Should be a boundary object
3rd column: Should be the control object that
manages the rest of the use case
• Creation of objects:
• Create control objects at beginning of event flow
• The control objects create the boundary objects
• Access of objects:
• Entity objects can be accessed by control and
boundary objects
• Entity objects should not access boundary or
control objects.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
:Tournament
Boundary :Arena :League
League
Owner

newTournament
(league)
:Announce
«new» Tournament
Control
checkMax
Tournament()
setName(name)

setMaxPlayers
(maxp)

commit() create
createTournament Tournament
(name, maxp) «new»
(name, maxp) :Tournament

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Let’sassume ARENA’s object model contains - at
this modeling stage - the objects
 League Owner, Arena, League, Tournament, Match and
Player

•The Sequence Diagram identifies 2 new Classes


• Tournament Boundary, Announce_Tournament_Control

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


League Owner League
1 *
Attributes Attributes
Operations Operations

Tournament
Attributes
Operations

Player Match
* *
Attributes Attributes
Operations Operations

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


League Owner League
1 *
Attributes Attributes
Operations Operations

Tournament_
Boundary
Attributes
Operations
Tournament
Announce_
Tournament_ Attributes
Control Operations

Attributes
Operations

Player Match
* *
Attributes Attributes
Operations Operations

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 The sequence diagram also supplies us with many
new events
newTournament(league)

 setName(name)
 setMaxPlayers(max)
 commit
 checkMaxTournament()
 createTournament
• Question:
• Who owns these events?
• Answer:
• For each object that receives an event there is a public
operation in its associated class
• The name of the operation is usually the name of the
event.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
:Tournament
Boundary :Arena :League
League
Owner

newTournament
(league)

:Announce
«new» Tournament
Control
checkMax
Tournament()
setName(name)

setMaxPlayers
(maxp)

commit() create
createTournament Tournament
(name, maxp) «new»
(name, maxp) :Tournament

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


League Owner League
1 *
Attributes Attributes
Operations Operations

Tournament_
Boundary
Attributes
Operations
Tournament
Announce_
Tournament_ Attributes
Control Operations
Attributes
createTournament
(name, maxp)

Player Match
* *
Attributes Attributes
Operations Operations

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Sequence diagrams are derived from use
cases

 The structure of the sequence diagram helps


us to determine how decentralized the
system is
 We distinguish two structures for sequence
diagrams
 Fork Diagrams and Stair Diagrams (Ivar Jacobsen)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 The dynamic behavior is placed in a single object, usually a
control object
 It knows all the other objects and often uses them for direct
questions and commands

Control
Object

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 The dynamic behavior is distributed. Each object delegates
responsibility to other objects
 Each object knows only a few of the other objects and knows which
objects can help with a specific behavior

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Object-oriented supporters claim that the
stair structure is better
 Modeling Advice:
 Choose the stair - a decentralized control
structure - if
 The operations have a strong connection
 The operations will always be performed in the same
order
 Choose the fork - a centralized control structure
- if
 The operations can change order
 New operations are expected to be added as a result
of new requirements.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
We already worked with interaction diagrams: System Sequence Diagrams

: System
User Timer
«initiating actor» «offstage actor»
select function(“unlock")

prompt for the key

enter key
verify key

signal: valid key, lock open


open the lock,
turn on the light

start ("duration“)

System Sequence Diagrams considered interactions between the actors

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 New concept of interaction fragments

 Before going into detail with interaction


fragments, we cover the concept of an
interaction

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 An Interaction is a concept providing a basis
for interaction diagrams:
 Sequence diagrams
 Communication diagrams
 Interaction overview diagrams
 Timing diagrams
 An interaction is a unit of behavior that
focuses on the observable exchange of
information between connectable elements.
 We only focus on the impact of interactions on
sequence diagrams

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 UML Interactions are used to get a better grip
of an interaction situation
 Interactions are also used during the detailed
design phase if precise inter-process
communication must be set up according to
formal protocols
 When testing is performed, the traces of the
system can be described as interactions and
compared with those of the earlier phases.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 The sequence diagram on the previous slide
shows three messages between two anonymous
lifelines of type User and ACSystem: CodePin,
CardOut and OK
 The message CardOut overtakes the message OK in
the way that the receiving event occurrences are in
the opposite order of the sending event occurrences.
 Such communication may occur when the messages
are asynchronous.
A fourth message Unlock is sent from the
ACSystem to the environment
 Through a gate with the implicit name out_Unlock.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 Interaction Fragment
 Is a piece of an interaction
 Acts like an interaction itself
 Combined Fragment
 Is a subtype of interaction fragment
 defines an expression of interaction fragments
 defined by an interaction operator and
corresponding interaction operands

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


A combined fragment defines an expression of
interaction fragments. The following operators are
allowed in an combined fragment expression:
 Alt  Neg
 Opt  Assert
 Strict
 Par
 Seq
 Loop  Ignore
 Critical  Consider

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 The interaction operator alt designates that the combined
fragment represents a choice of behavior.
 At most one of the operands will be chosen. The chosen
operand must have an explicit or implicit guard expression that
evaluates to true at this point in the interaction. An implicit true
guard is implied if the operand has no guard.
 The set of traces that defines a choice is the union of the
(guarded) traces of the operands.
 An operand guarded by else designates a guard that is the
negation of the disjunction of all other guards in the enclosing
combined fragment.
 If none of the operands has a guard that evaluates to true,
none of the operands are executed and the remainder of the
enclosing interaction fragment is executed.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 Option: The interaction operator opt designates a choice of
behavior where either the (sole) operand happens or nothing
happens.
 Break: The interaction operator break represents a breaking
scenario: The operand is a scenario that is performed instead of
the remainder of the enclosing interaction fragment.
 A break operator with a guard is chosen when the guard is true
 When the guard of the break operand is false, the break
operand is ignored and the rest of the enclosing interaction
fragment is chosen.
 The choice between a break operand without a guard and the
rest of the enclosing interaction fragment is done non-
deterministically.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Parallel: The interaction operator par designates a parallel
merge between the behaviors of the operands of a combined
fragment.
 The event occurrences of the different operands can be
interleaved in any way as long as the ordering imposed by each
operand is preserved.
 A parallel merge defines a set of traces that describes all the
ways that event occurrences of the operands may be
interleaved.
 Critical: The interaction operator critical designates that the
combined fragment represents a critical region.
 The traces of the region cannot be interleaved by other event
occurrences (on the Lifelines covered by the region). This
means that the region is treated atomically by the enclosing
fragment.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


The Operator must make sure to forward a 911-call to the Emergency object
before doing anything else. Normal calls can be freely interleaved.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 In this example, time constraints are associated with the duration
of a Message and the duration between two event occurrences.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Design
Sequence Diagram

System Sequence Diagram

Controller : Checker : KeyStorage : LockCtrl

User
«initiating actor»
ystem
: System
Timer
«offstage actor»
checkKey()
sk := getNext()
select function(“unlock")

prompt for the key


alt val != null setOpen(true)
enter key
verify key

signal: valid key, lock open


open the lock, [else] val == null : setLit(true)
turn on the light

start ("duration“)

• System Sequence Diagrams considered interactions between the actors


• Object Sequence Diagrams consider interactions between the objects
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
:InterfacePage :SearchRequest :Controller :PageMaker :DatabaseConn :Archiver :Notifier :InvestigRequest
Resident Database Landlord

We start with objects/concepts from the Domain Model


and modify or introduce new objects, as needed to
make the system function work.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 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)
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Starting Points: Domain Model from UC-1 (domain concepts):
Symbolizes Symbolizes
“worker”-type “thing”-type
Use Case UC-1: Unlock (flow of events): concept.
«entity»
concept.
«entity»
KeyStorage
1. User enters the key code
KeyChecker

2. System verifies that the key is valid «boundary»


KeycodeEntry
«entity»
Key
3. System signals the key validity
4. System signals: «boundary» «control»
(a) to LockDevice to disarm the lock StatusDisplay Controller LockDevice
«boundary»
(b) to LightSwitch to turn the light on HouseholdDeviceOperator

Scenario Walkthrough: User LightSwitch

for mapping a Use Case scenario to the Domain Model


Q: who handles this data?

Interface objects and Controller message: checkKey(k)

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

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

Q: who signals? Based on what data?


Controller and Interface objects, based on key verification; because they are «boundary»
Q: who signals? Based on what data?
Controller or Key checker ???, based on key verification
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
? ? : DatabaseConn : PageMaker : Controller : Checker : DeviceCtrl

checkKey()
accessList := retrieve(params : string)

R1.
interfacePage := activate( "lock" )
render(accessList : string) ?
R2.

(a) (b)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


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 key-code is-valid activation-params

Controller Checker Controller LockCtrl

“expert” on key validity

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

 Balanced workload across the objects

method_1() method_1()
method_2()

 Low degree of connectivity (associations)


method_N()

among the objects

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Supplement Reading

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 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 …


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 Goal:Reduce system complexity while allowing
change
 Coherence measures dependency among classes
 High coherence: The classes in the subsystem perform
similar tasks and are related to each other via many
associations
 Low coherence: Lots of miscellaneous and auxiliary
classes, almost no associations
 Coupling measures dependency among subsystems
 High coupling: Changes to one subsystem will have high
impact on the other subsystem
 Low coupling: A change in one subsystem does not affect
any other subsystem.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Good Design
 Goal:Reduce system complexity while allowing
change
 Coherence measures dependency among classes
 High coherence: The classes in the subsystem perform
similar tasks and are related to each other via
associations
 Low coherence: Lots of miscellaneous and auxiliary
classes, no associations
 Coupling measures dependency among subsystems
 High coupling: Changes to one subsystem will have high
impact on the other subsystem
 Low coupling: A change in one subsystem does not affect
any other subsystem
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 High coherence can be achieved if most of the
interaction is within subsystems, rather than across
subsystem boundaries
 Questions to ask:
 Does one subsystem always call another one for a
specific service?
 Yes: Consider moving them together into the same subystem.
 Which of the subsystems call each other for services?
 Can this be avoided by restructuring the subsystems or
changing the subsystem interface?
 Can the subsystems even be hierarchically ordered (in
layers)?

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Low coupling can be achieved if a calling class
does not need to know anything about the
internals of the called class (Principle of
information hiding, Parnas)
 Questions to ask:
 Does the calling class really have to know any
attributes of classes in the lower layers?
 Is it possible that the calling class calls only operations
of the lower level classes?

David Parnas, *1941,


Developed the concept of
modularity in design.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


: Controller : Checker : DevCtrl : Controller : Checker : DevCtrl

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


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
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
«html»
interfacePage : : Controller : PageMaker : DatabaseConnection
Resident Database

specify get( queryRequest : string )


query accessList := retrieve(params : string)
request retrieve records

result

interfacePage := render(accessList : string)

alt accessList != NULL


page :=
renderList()

[else] page :=
warning()

result «post page»


displayed

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


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

checkKey()
sk := getNext()

alt val != null setOpen(true)

[else] val == null : setLit(true)

logTransaction(val)

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


: Controller k : Key : Checker : KeyStorage : DeviceCtrl : PhotoObsrv : Logger

enterKey()
«create»

loop [for all stored keys]


val := checkKey( k )
sk := getNext()

compare(k, sk)

logTransaction( k, val )
«destroy»

alt val == true activate( "lock" )

dl := isDaylight()

opt dl == false activate( "bulb" )

[else] numOfAttempts++

alt numOfAttempts == maxNumOfAttempts


denyMoreAttempts()

activate( "alarm" )

[else]

prompt: "try again"

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


: Controller k : Key : Checker : KeyStorage : LockCtrl

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!!

Sets a boolean attribute of the Key object: ok = true/false;


Business logic (IF-THEN rule) relocated from Controller to LockCtrl
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
: LightCtrl : PhotoSObs : LightCtrl : PhotoSObs

controlLight() checkIfDaylightAndIfNotThenSetLit()
dl := isDaylight() dl := isDaylight()

opt dl == false The caller opt dl == false


could be
Controller or
setLit(true) KeyChecker setLit(true)

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


c
: Controller k : Key : Checker : KeyStorage : DeviceCtrl : PhotoObsrv : Logger
: DeviceCtrl : PhotoSObs
enterKey()
k := create()

loop [for all stored keys]


val := checkKey(k)
sk := getNext()

compare()
activate( "light" )
logTransaction(k, val) dl := isDaylight()
«destroy»

alt val == true activate(“lock”)

opt dl == false
dl := isDaylight()

a opt dl == false activate(“bulb”) setLit(true)

: Controller k : Key [else]


: Checker
numOfTrials++ : KeyStorage : DeviceCtrl
prompt:
"try again"
k := create()
opt numOfTrials == maxNumOfTrials activate(“alarm”)

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)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


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
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
System Design
8. Boundary
1. Design Goals Conditions
Definition Initialization
Trade-offs Termination
Failure
2. Subsystem 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 Persistent Objects Access Control List
Buy vs Build File system vs Database vs Capabilities
Allocation of Resources Security
Connectivity

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Nonfunctional Requirements to be addressed:
Performance, Response time, latency,
availability.
 Two objects are inherently concurrent if they
can receive events at the same time without
interacting
 Source for identification: Objects in a sequence
diagram that can simultaneously receive events
 Unrelated events, instances of the same event
 Inherently concurrent objects can be assigned to
different threads of control
 Objects with mutual exclusive activity could be
folded into a single thread of control

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 A thread of control is a path through a set of
state diagrams on which a single object is active
at a time
 A thread remains within a state diagram until an
object sends an event to different object and waits
for another event
 Thread splitting: Object does a non-blocking send of
an event to another object.
 Concurrent threads can lead to race conditions.
 A race condition (also race hazard) is a design
flaw where the output of a process is depends on
the specific sequence of other events.
 The name originated in digital circuit design: Two
signals racing each other to influence the output.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Assume: Initial
balance = 200

:WithdrawCtrl :BankAccount :WithdrawCtrl


c1:Customer c2:Customer

withdraw(50)
getBalance()

Thread 1 200 withdraw(50)


getBalance()
computeNewBalance(200,50)
200 Thread 2
computeNewBalance(200,50)

setBalance(150)

setBalance(150)

Should BankAccount
be another Thread ?

Final
balance = 150 ??!

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Synchronized method
Single WithdrawCtrl Initial
Instance balance = 200

:WithdrawCtrl :BankAccount
c1:Customer c2:Customer

withdraw(50)
getBalance()
withdraw(50)
200

computeNewBalance(200,50)

setBalance(150)

End
balance = 100

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 To identify threads for concurrency we ask
the following questions:
 Does the system provide access to multiple users?
 Which entity objects of the object model can be
executed independently from each other?
 What kinds of control objects are identifiable?
 Can a single request to the system be
decomposed into multiple requests? Can these
requests and handled in parallel? (Example: a
distributed query)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Concurrent systems can be implemented on
any system that provides
 Physical concurrency: Threads are provided by
hardware
or
 Logical concurrency: Threads are provided by
software
 Physical concurrency is provided by
multiprocessors and computer networks
 Logical concurrency is provided by threads
packages.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 In both cases, - physical concurrency as well as logical
concurrency - we have to solve the scheduling of
these threads:
 Which thread runs when?
 Today’s operating systems provide a variety of
scheduling mechanisms:
 Round robin, time slicing, collaborating processes, interrupt
handling
 General question addresses starvation, deadlocks,
fairness -> Topic for researchers in operating systems
 Sometimes we have to solve the scheduling problem
ourselves
 Topic addressed by software control.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Object Oriented Design
-Object Design
-Class Diagram Design
Manuel Medina
CMPS 4131
University of Belize

 Object Design Activities


 Visibilities
 Information Hiding
 The use of inheritance
 Implementation vs. specification inheritance
 Delegation vs. Inheritance
 Abstract classes and abstract methods
 Overwriting methods
 Contraction: Bad example of inheritance
 Specifying Operations Signatures

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Understand visibility and why it is


important.
 Draw a complete design class diagram.
 Measure the design quality using the
properties of cohesion, coupling, and the
Law of Demeter.
 Write the method signatures.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

 Step 2 of object-oriented program design


produces a design class diagram based
on the interaction diagrams.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 A design class diagram is a static model


of the entire system.

 It combines the interaction diagrams to


show only the links between classes and
the direction of visibility between
classes.

© 2023 Prentice Hall - Slides Modified for CMPS4131

3
 Step 3 of object-oriented program
design specifies precisely the
composition of each message and
the algorithm for each operation in
the program.

 At this point, the design of the software


in the business layer is complete.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 A design class diagram follows the same


UML graphic conventions as a domain
model.
 A design class diagram shows:
 Classes and class hierarchies
 Attributes
 Operations
 Whole-to-part associations
 Qualified associations

© 2023 Prentice Hall - Slides Modified for CMPS4131

4
 A qualified association associates two
objects using a qualifier to select objects
at the other end of the association.

 A qualifier is an attribute or set of


attributes which has a unique value
for each object in the class.

© 2023 Prentice Hall - Slides Modified for CMPS4131

FIGURE 9.2

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

System design gap

Machine
© 2023 Prentice Hall - Slides Modified for CMPS4131

6
Call the Class
Class User

Developer Class Implementor Realize the Class


(Implement it)

Class Extender Refine the Class


(Implement a
subclass)

© 2023 Prentice Hall - Slides Modified for CMPS4131

The Developer responsible


The developer responsible for the implementation of
for the implementation of Game is a class implementor
League is a class user of Game

League Game
1

*
Tournament TicTacToe Chess

The developer responsible for


the implementation of TicTacToe
is a class extender of Game

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Visibility is the ability of one object


to have a reference to (to “see”)
another object. This reference
is the object’s internal identifier.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

Class User Call Class

Developer Class Implementor Realize Class

Class Extender Refine Class

Class user (“Public”): +


 Public attributes/operation can be accessed by any class
Class implementor (“Private”): -
 Private attributes and operations can be accessed only
by the class in which they are defined
 They cannot be accessed by subclasses or other classes
Class extender (“Protected”): #
 Protected attributes/operations can be accessed by the
class in which they are defined and by any descendent of
the class.
© 2023 Prentice Hall - Slides Modified for CMPS4131

9
Tournament

- maxNumPlayers: int
+ getMaxNumPlayers():int
+ getPlayers(): List
+ acceptPlayer(p:Player)
+ removePlayer(p:Player)
+ isPlayerAccepted(p:Player):boolean

public class Tournament {


private int maxNumPlayers;
public Tournament(League l, int maxNumPlayers)
public int getMaxNumPlayers() {…};
public List getPlayers() {…};
public void acceptPlayer(Player p) {…};
public void removePlayer(Player p) {…};
public boolean isPlayerAccepted(Player p) {…};

© 2023 Prentice Hall - Slides Modified for CMPS4131

Hashtable
numElements:int
put()
get()
remove()
containsKey()
size()

Attributes and operations Hashtable


without visibility and -numElements:int
type information are ok during +put(key:Object,entry:Object)
requirementsanalysis +get(key:Object):Object
+remove(key:Object)
+containsKey(key:Object):boolean
During object design, we +size():int
decide that the hash
table can handle any
type of keys, not only
Strings.
© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

Step 4. Design the graphical user


interface.
Step 5. Define the interface to the
presentation layer.
Step 6. Define the interface to the storage
layer.
Step 7. Place the classes in packages.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

Identify classes with their behavior.


FIGURE 9.9

© 2023 Prentice Hall - Slides Modified for CMPS4131

12
Identify classes with their behavior.
FIGURE 9.9
(continued)

© 2023 Prentice Hall - Slides Modified for CMPS4131

Add inheritance to the class diagram.


FIGURE 9.11

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Inheritance is used to achieve two different goals


 Description of Taxonomies
 Interface Specification
 Description of Taxonomies
 Used during requirements analysis
 Activity: identify application domain objects that are
hierarchically related
 Goal: make the analysis model more understandable
 Interface Specification
 Used during object design
 Activity: identify the signatures of all identified objects
 Goal: increase reusability, enhance modifiability and
extensibility
© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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() }

© 2023 Prentice Hall - Slides Modified for CMPS4131

15
Inheritance is used in four ways:

 Specialization
 Generalization
 Specification
Inheritance
 Implementation Inheritance.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 To“discover“ inheritance associations, we


can proceed in two ways, which we call
specialization and generalization

 Generalization: the discovery of an


inheritance relationship between two
classes, where the sub class is discovered
first.
 Specialization: the discovery of an
inheritance relationship between two
classes, where the super class is discovered
first.
© 2023 Prentice Hall - Slides Modified for CMPS4131

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?

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

 Specializationoccurs, when we find a subclass that is


very similar to an existing class.
 Example: A theory postulates certain particles and events
which we have to find.(Physics – search particles)
 Specialization can also occur unintentionally:

© 2023 Prentice Hall - Slides Modified for CMPS4131

18
Car Airplane

drive() fly()

Airplane Car

fly() drive()

© 2023 Prentice Hall - Slides Modified for CMPS4131

VendingMaschine CandyMachine is a new


product and designed as a sub
totalReceipts class of the superclass
VendingMachine
collectMoney()
makeChange()
dispenseBeverage() A change of names might now
be useful: dispenseItem()
instead of
dispenseBeverage()
and
dispenseSnack()

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

A very similar class is already implemented that does


almost the same as the desired class implementation
List
Example: Add()
• I have a List class, I need a Remove()
Stack class “Already
• How about subclassing the implemented”
Stack class from the List
class and implementing Stack
Push(), Pop(), Top() with Push()
Add() and Remove()? Pop()
Top()
Problem with implementation inheritance:
• The inherited operations might exhibit unwanted behavior.
• Example: What happens if the Stack user calls Remove()
instead of Pop()?
© 2023 Prentice Hall - Slides Modified for CMPS4131

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

+Add() Stack List


+Remove()
+Push() Add()
+Pop() Remove()
Stack +Top()

+Push()
+Pop()
+Top()
© 2023 Prentice Hall - Slides Modified for CMPS4131

 Delegation is a way of making composition as


powerful for reuse as inheritance
 In delegation two objects are involved in handling
a request from a Client
•The Receiver object delegates operations to
the Delegate object
•The Receiver object makes sure, that the
Client does not misuse the Delegate object.

Client Receiver delegates to Delegate


calls

© 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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

 Rewriteable Method: A method which allow a


reimplementation.
 In Java methods are rewriteable by default, i.e.
there is no special keyword.
 Strict inheritance
 The subclass can only add new methods to the
superclass, it cannot over write them
 If a method cannot be overwritten in a Java
program, it must be prefixed with the keyword
final.

© 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

Original Java-Code: help() not


overwritable
class Device {
int serialnr;
public final void help() {….}
public void setSerialNr(int n) {
serialnr = n;
} setSerialNr()
} overwritable
class Valve extends Device {
Position s;
public void on() {
….
}
}

© 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()

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

© 2023 Prentice Hall - Slides Modified for CMPS4131

One can overwrite the operations of a superclass with


completely new meanings.

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!!

© 2023 Prentice Hall - Slides Modified for CMPS4131

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()

Existing Class: Boombox:


public class Auto {
public class Boombox
public void drive() {…} extends Auto {
public void brake() {…} public void drive() {};
public void accelerate() {…}
public void brake() {};
public void playMusic() {…}
public void accelerate()
public void ejectCD() {…} {};
public void resumeMusic() {…}
}
public void pauseMusic() {…}
}

© 2023 Prentice Hall - Slides Modified for CMPS4131

Add associations to the class diagram.


FIGURE 9.13

© 2023 Prentice Hall - Slides Modified for CMPS4131

29
Create a FIGURE 9.15

final class
diagram
with
qualified
associations.

© 2023 Prentice Hall - Slides Modified for CMPS4131

SUPPLEMENT READING

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Only the operations of a class are allowed to


manipulate its attributes
 Access attributes only via operations
 Hide external objects at subsystem boundary
 Define abstract class interfaces which mediate
between the external world and the system as
well as between subsystems
 Do not apply an operation to the result of
another operation
 Write a new operation that combines the two
operations.

© 2023 Prentice Hall - Slides Modified for CMPS4131

31
There are three common guidelines for assessing
and improving the quality of object-oriented
program design:

 Cohesion
 Coupling
 The Law of Demeter

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Coupling measures how strongly one class is


connected to, has knowledge of, or relies on
other objects.

 It is desirable to have objects with low coupling.

 Giving too much responsibility to the façade


object leads to poor coupling.
 The higher the interdependency, the more likely
changes in part of a design can cause changes to be
required in other parts of the design.

© 2023 Prentice Hall - Slides Modified for CMPS4131

32
Subclasses are strongly connected to their
superclasses.

Other sources of coupling are classes which


have:
 A reference to another class or an object
in that class.
 A method which references another class
or an object in that class.
 An association with another class.

© 2023 Prentice Hall - Slides Modified for CMPS4131

.
FIGURE 9.17

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

© 2023 Prentice Hall - Slides Modified for CMPS4131

34
© 2023 Prentice Hall - Slides Modified for CMPS4131

© 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

© 2023 Prentice Hall - Slides Modified for CMPS4131

 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

© 2023 Prentice Hall - Slides Modified for CMPS4131

36
© 2023 Prentice Hall - Slides Modified for CMPS4131

© 2023 Prentice Hall - Slides Modified for CMPS4131

37
© 2023 Prentice Hall - Slides Modified for CMPS4131

FIGURE 9.18
.

© 2023 Prentice Hall - Slides Modified for CMPS4131

38
Data type is the UML term for the
description of an attribute of a class.

Data types are either primitive data types or


value objects.

A primitive data type can be represented


directly in computer hardware – integer,
floating point, or character.

© 2023 Prentice Hall - Slides Modified for CMPS4131

A value object is an object whose


unique identity is not meaningful.

A reference object is an object whose


unique identity is meaningful.

Reference objects are never shown


as attributes in a class diagram;
they are shown as associations.

© 2023 Prentice Hall - Slides Modified for CMPS4131

39
A signature is a specification of
an operation which describes
completely the interface of the
operation.

This comprises the operation’s:


 name, and
 every input and output with its
data type.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Attributes are described as:

- name : data type

 Where the first symbol represents the


attribute’s visibility:
- for private
+ for public
# for protected

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

© 2023 Prentice Hall - Slides Modified for CMPS4131

FIGURE 9.23

© 2023 Prentice Hall - Slides Modified for CMPS4131

41
FIGURE 9.25

© 2023 Prentice Hall - Slides Modified for CMPS4131

SUPPLEMENT READING

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Contract:A lawful agreement between two parties in


which both parties accept obligations and on which
both parties can found their rights
 The remedy for breach of a contract is usually an award of
money to the injured party
 Object-orientedcontract: Describes the services that
are provided by an object if certain conditions are
fulfilled
 services = “obligations”, conditions = “rights”
 The remedy for breach of an OO-contract is the generation
of an exception.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

 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 that is
provided.
 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 Germany
within 4 hours of pickup.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Contracts enable the caller and the provider to


share the same assumptions about the class
 A contract is an exact specification of the interface
of an object
 A contract include three types of constraints:
 Invariant:
 A predicate that is always true for all instances of a class
 Precondition (“rights”):
 Must be true before an operation is invoked
 Postcondition (“obligation”):
 Must be true after an operation is invoked.

© 2023 Prentice Hall - Slides Modified for CMPS4131

45
A contract is called a formal specification, if
the invariants, rights and obligations in the
contract are unambiguous.

© 2023 Prentice Hall - Slides Modified for CMPS4131

A constraint can also be depicted as a note


attached to the constrained UML element by
a dependency relationship.
<<invariant>>
<<precondition>> numElements >= 0
!containsKey(key) HashTable
numElements:int
put(key,entry:Object) <<postcondition>>
get(key):Object get(key) == entry
remove(key:Object)
<<precondition>> containsKey(key:Object):boolean
containsKey(key) size():int

<<precondition>> <<postcondition>>
containsKey(key) !containsKey(key)

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

 Constraints are sometimes used during


requirements analysis, however there are trade
offs

© 2023 Prentice Hall - Slides Modified for CMPS4131

 Communication among stakeholders


 Can the client understand formal constraints?
 Level of detail vs. rate of requirements change
 Is it worth precisely specifying a concept
that will change?
 Level of detail vs. elicitation effort
 Is it worth the time interviewing the end user
 Will these constraints be discovered during object
design anyway?
 Testing constraints
 If tests are generated early, do they require this level of
precision?
© 2023 Prentice Hall - Slides Modified for CMPS4131

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.

© 2023 Prentice Hall - Slides Modified for CMPS4131

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


REQ1: Keep door locked and auto-lock
REQ2: Lock when “LOCK” pressed
REQ3: Unlock when valid key provided
REQ4: Allow mistakes but prevent dictionary attacks
REQ5: Maintain a history log
REQ6: Adding/removing users at runtime
REQ7: Configuring device activation preferences
REQ8: Inspecting the access history
REQ9: Filing inquiries

PROBLEM DOMAIN

(5) Device
(6) Photosensor preferences
(7) Light
(3) Key

(1) Tenant (4) List of


valid keys
(3) Lock

(8) Alarm bell (11) Log of


accesses
Software-to-be

(2) Landlord
(10) Tenant
(9) Desktop computer accounts

Difficult to consider the whole system at once…


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
REQ1: Keep door locked and auto-lock
REQ2: Lock when “LOCK” pressed
REQ3: Unlock when valid key provided
REQ4: Allow mistakes but prevent dictionary attacks
REQ5: Maintain a history log
REQ6: Adding/removing users at runtime
REQ7: Configuring device activation preferences
REQ8: Inspecting the access history REQ1, REQ2,
REQ9: Filing inquiries REQ3 REQ3, REQ4
PROBLEM DOMAIN

(5) Device
(6) Photosensor preferences
(7) Light
Subsystem-2
(3) Key

(1) Tenant (4) List of


Subsystem-1
valid keys
(3) Lock

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

⇒ Decompose the system based on its requirements


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
PROBLEM WORLD & DOMAINS (PARTS)

(5) Device
(6) Photosensor
preferences
(3) Key
(7) Light

(1) Tenant (4) List of


valid keys
(3) Lock

(8) Alarm bell (11) Log of


accesses
Software-to-be

(2) Landlord
(10) Tenant
(9) Desktop computer accounts

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


PROBLEM WORLD & DOMAINS (PARTS)

(5) Device
(6) Photosensor
preferences
(3) Key
(7) Light

(1) Tenant (4) List of


valid keys
(3) Lock

(8) Alarm bell (11) Log of


accesses
Software-to-be

(2) Landlord
(10) Tenant
(9) Desktop computer accounts

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


(5) Device
(6) Photosensor
preferences
(3) Key
(7) Light

(1) Tenant (4) List of


valid keys
(3) Lock

(8) Alarm bell (11) Log of


accesses
Software-to-be

(2) Landlord
(10) Tenant
(9) Desktop computer accounts

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


A phenomenon is a fact, or object, or
occurrence that appears or is perceived to exist
 An event is an individual happening,
occurring at a particular point in time
 Events are indivisible and instantaneous
A state is a relation among individual entities
and values, which can change over time
 Individuals are in relation if they share a
certain characteristic
 RelationName(Individual1, …, Individualn)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Events take place at transitions between the states

2 Event: Kick

Elevation of the ball


3 State:
Ball flying
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

Relation: Neighbors (Person_i, Person_j)


Set of all 3-tuples of bread slices
and ham

Set of sandwiches

Relation:
Sandwich (Bread-slice, Ham-slice, Bread-slice)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


State 1: NotPowered (the player is not powered up)
State 2: Powered (the player is powered up)
State 3: Loaded (a disc is in the tray)
State 4: Playing

State 1: NotPoweredEmpty (the player is not powered up and contains no disc)


State 2: NotPoweredLoaded (the player is not powered up and a disc is in the tray)
State 3: PoweredEmpty (the player is powered up and contains no disc)
State 4: PoweredLoaded (the player is powered up and a disc is in the tray)
State 5: Playing

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


(Level of detail)

DVD player

Power Disc
button tray

DVD player Play


button …

Atomic object Object composed of parts

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


System Part (Object) State Relations

Power button {Off, On}

Disc tray {Empty, Loaded}

Play button {Off, On}

… …

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


State variable = a physical part or an attribute of an object

State Variable State Relations

Door lock {Disarmed, Armed}

Light bulb {Unlit, Lit}

Counter of failed attempts {0, 1, …, maxNumOfAttempts}

Auto-lock timer {0, 1, …, autoLockInterval}

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Observable state:
apple’s appearance

Goal:

Find the likelihood of


different hidden states,
for given observable
Hidden state: states
contains a worm

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Objects of a class in a class diagram may
change state in response to an event
 Different states are captured in this model
 Shows the different states through which a single object
passes during its life
 May include the object’s responses and actions

 Example: patient states can change over time


 New patient—has not yet been seen
 Current patient—is now receiving treatment
 Former patient—no longer being seen or treated

 Typically used only for complex objects not


all objects.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 We distinguish between two types of
operations:
 Activity: Operation that takes time to complete
 associated with states
 Action: Instantaneous operation
 associated with events
A state chart diagram relates events and
states for one class “Descriptive”
 An object model with several classes with
interesting behavior has a set of state
diagrams

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Name of
Action
Event with parameters attr State

State1 Event(attr)
Event [condition]/action State2
do/Activity
entry /action Guard
condition
exit/action

 Note: Actions and Activities in State


 Events are italics
 Conditions are enclosed with brackets: []
 Actions and activities are prefixed with a slash /
 Notationis based on work by Harel
 Added are a few object-oriented modifications.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


coins_in(amount) / set balance
Collect Money
Idle coins_in(amount) / add to balance
cancel / refund coins

[item empty] [select(item)] [change<0]

do/Test item and compute change


[change=0] [change>0]

do/Dispense item do/Make change

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 An abstraction of the attributes of a class
 State is the aggregation of several attributes a
class
A state is an equivalence class of all those
attribute values and links that do no need to
be distinguished
 Example: State of a bank
 State has duration

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 State chart diagrams help to identify:
 Changes to an individual object over time

 Sequence diagrams help to identify:


 The temporal relationship of between objects
over time
 Sequence of operations as a response to one ore
more events.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 States—values of an object’s attributes at a point in
time, state has duration
 Events—the cause of the change in values of the
object’s attributes
 Transitions—movement of an object from one state
to another
 May include a guard condition to flag that a condition is true and
allow the transition

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


 Statechart diagrams can be used for the
design of user interfaces
 States: Name of screens
 Actions or activities are shown as bullets
under the screen name

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Screen name

Action or
Activity Diagnostics Menu
•User moves cursor to Control Panel or Graph

Control panel Graph


• User selects functionality of sensors • User selects data group
and type of graph
Define
• User defines a sensor event
from a list of events Selection
• User selects data group
Enable Disable • Field site
• User can enable • User can disable a • Car
a sensor event sensor event from • Sensor group
from a list of a list of sensor events • Time range
sensor events
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
 Use only for complex objects
 Draw the initial state in the upper left corner
 Draw the final state in the bottom right corner
 Use simple, but descriptive names for states
 Look out for “black holes” and “miracles”
 Ensure guard conditions are mutually exclusive
 Ensure transitions are associated with messages
and operations

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


• Set the context
• Identify the states of the object
• Initial
• Final
• Stable states during its lifetime

• Lay out the diagram—use a left to right sequence


• Add the transitions
• Identify the triggers (events that cause the transition)
• Identify the actions which execute
• Identify the guard conditions

• Validate the model—ensure all states are


reachable
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Market
index
Market
Open Closed 1.00 1.01 1.02
gate

Stock_1_Price Stock_1_Shares Stock_2_Price Stock_2_Shares

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 )

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Events marking transitions between the states of a trading order:

submit matched archive

InPreparation Pending Executed Archived

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

Label Propositions (they complete the above list)


p The investor requests to place a market order
q The investor is shown a blank ticket where the trade can be specified (action, symbol, etc.)
r The most recently retrieved indicative price is shown in the currently open order ticket
s The symbol SYM specified by the investor is a valid ticker symbol
t The current indicative price that is obtained from the exchange
u The system executes the trade
v The system calculates the player’s account new balance
w The system issues a confirmation about the outcome of the transaction
x The system archives the transaction
REQ2 represented as a set of propositions
p⇒q∧r
s
y = v ∧ {¬(n ∨ o) ∨ [(o ∧ p ∨ ¬o ∧ q) ∧ (∃ IP)(LB ≤ IP ≤ UB)]}
z = ¬m ∨ {[¬n ∧ (VOL × IP ≤ BAL)] ∨ [n ∧ (VOL × UB ≤ BAL)]}
y∧z⇒u
u⇒v∧w∧x
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
States of Stock_i

event
trade bankruptcy,
merger,
initial-listing acquisition, …
Listing
Traded Delisted
planned

transition
initial state terminal state

indicated by indicated by

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


trade bankruptcy,
merger,
initial-listing acquisition, …
Listing
Traded Delisted
planned

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


States of a Trading Order

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


[ Read 2.7.2: Test Coverage and Code Coverage ]

User leaves without succeeding or blocking


invalid-key [numOfAttemps ≤ maxNumOfAttempts] /
signal-failure

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

Need “entry” and “do” state activities


for countdown timers
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
Problem:
- but a guest may be occupying the room
make-reservation / while it is reserved by a future guest!?
Reserved
- or the room may be vacant
while reserved by a future guest!?

Vacant arrive /

depart /
Occupied

⇒ need a notion of time (“timing diagram”)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


C make-reservation
B make-reservation
Reserved Reserved
by guest B by guest C
Reserved
States

Occupied

Vacant

Time [days]
A depart

B depart
C arrive

C depart
A arrive

B arrive

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


C make-reservation
B make-reservation
♦ What if the guest is late? – “Holding” state?
♦ What if the room is overbooked?
Reserved Reserved
♦ What when it is being cleaned?
by guest B by guest C
Reserved
Issue: state transitions are
What state? weird—”Reserved” is a
future state but
Occupied transitioned to by a
current event!

Vacant

Time [days]
A depart

B depart

C depart
A arrive

B arrive

C arrive

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


C make-reservation
SOLUTION:

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

Objects send messages that change states


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131
We need two objects:
One tracks room’s current state (occupancy)
and the other its future state (reservation)

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131


Software Design
*Design Concepts
*Architecture Patterns

Manuel Medina
CMPS 4131
University of Belize

 Overview of System Design

 Software Architecture Definition

 Architectural Decisions & Key Concerns

 Subsystem Decomposition

 Problem Decomposition & Problem Architecture

 Architectural Styles

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 2

1

As a software engineer, we need
to have a capability for
choosing/tailoring process
models for a specific project.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 3

 “There is definitely a need for people to learn kind of a computer


science way of thinking about problems, but not necessarily the
language du jour ,” says Erik Brynjolfsson , a professor at the MIT
Sloan School of Management
 Irving W ladawsky Berger , formerly of IBM and now at New York
University, “We should definitely teach design . This is not
coding, or even programming. It requires the ability to think
about the problem, organize the approach, know how to use
design tools.”
 But, by 2030’s, when today’s 10 year olds are in the job market,
they’ll need to be creative, problem solving design thinkers who
can teach a machine how to do things.

 http://www.newsweek.com/2014/06/06/computer-
programming-dying-art-252618.html

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 4

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.

 The next generation of computers will learn from their


interactions with data and people.

 In another decade or so, we won’t program computers we’ll


teach them

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 5

 “There are two ways of constructing a


software design:
 one way is to make it so simple that there are
obviously no deficiencies;
 the other is to make it so complicated that there
are no obvious deficiencies.” [Tony Hoare]

 Goals: separation of concerns and modularity.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 6

3
A process to transform user requirements into
some suitable form, which helps the
programmer in software coding.

 Software design is the first step, which moves


the concentration from problem domain to
solution domain . It tries to specify how to
fulfill the requirements mentioned in SRS.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 7

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 8

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

 Verification and validation

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 9

 Example: Linux Kernel


 16 million Lines of Code!
 What does the code do?
 Are there dependencies?
 Are there different components?

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 10

5
 Example: Linux Kernel
 16 million Lines of Code!
 What does the code do?
 Are there dependencies?
 Are there different components?

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 11

What’s the difference?


Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 12

6
 Architecture (what is developed?)
 High-level view of the overall system:
 What components do exist?

 What are the protocols between components?

 What type of storage etc.?

 Design (how are the components developed?)


 Considers individual components:
 Data representation

 Interfaces, Class hierarchy

 …

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 13

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 14

7
 Drawing a picture vs. Programming/Software
Engineering
 Let us discuss Similarity vs. Difference

 What/How to learn to be a good software


designer?
 Let us discuss

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 15

 Design in Software Development


 For a given set of requirements, the so(ware development team
must design a system that will meet those requirements.
 This has many aspects:
 system architecture
 program design
 security
 performance
 Design was also an important part of the lectures on usability.
 In practice requirements and design are interrelated. In
particular, working on the design often clarifies the
requirements. This feedback is a strength of the iterative and
agile methods of software development.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 16

8
 Creativity and design

 System and program design are a particularly creative part of


software development, as are user interfaces.

 Above all strive for simplicity. The aim is find simple


ways to implement complex requirements. You hope that
people will describe your designs as “elegant”, “easy to
implement, test, and maintain.”

 Software development as a c r a f t :

 Software development is a c ra f t : Software developers


have a variety of tools that can be used in design, but you
have to select the appropriate tool for a given
implementation.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 17

 System architecture is the overall design of a system:


 Computers and networks (e.g., in-house computers,
cloud services)
 Interfaces and protocols (e.g., http, IMAP, ODBC)
 Databases (e.g., relational, distributed)
 Security (e.g., Shibboleth)
 Operations (e.g., backup, archiving, audit trails)
 At this stage of the development process, you should
also be selecting:
 Software environments (e.g., languages, database
systems, class frameworks)
 Testing frameworks
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 18

9
product line
product or system architecture decisions
architecture decisions
systemic impact
Product line scope

Product/system A scope Product B scope

Subsystem scope
local impact
Class scope

• Given the current level of system scope, a decision


is “architectural” if it can be made only by
considering the present scope
– I.e. could not be made from a more narrowly-scoped, local perspective
– Architectural decisions should focus on high impact, high priority areas
that are in strong alignment with the business strategy
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 19

Safe Home Access System

Subsystem Subsystem Subsystem


Decision on system
for device for for remote
control administration data access decomposition

On embedded On office On tenant’s Decision on software-to-


computer desktop smartphone hardware mapping

Such decisions are made early on,


perhaps while discussing the requirements with the customer
to decide which hardware devices will be used for user interaction and device control

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 20

10
 Architecture focuses on non-functional
requirements (“cross-cutting concerns”) and
decomposition of functional requirements

 Design focuses on implementing the functional


requirements

 Note: The borders are not always sharp!

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 21

 The “best” design for a component


considered in isolation may not be chosen
when components considered together or
within a broader context
 Plus, business priorities, available resources,
core competences, target customers,
competitors’ moves, technology trends, existing
investments, backward compatibility, …

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 22

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 23

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 26

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 27

 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

 Reliability Good documentation


 Modifiability Well-defined interfaces
 Maintainability User-friendliness
 Understandability Reuse of components
 Adaptability Rapid development
 Reusability Minimum number of errors
 Efficiency Readability
 Portability Ease of learning
Ease of remembering
 Traceability of requirements
Ease of use
 Fault tolerance
Increased productivity
 Backward-compatibility
Low-cost
 Cost-effectiveness
Flexibility
 Robustness
 High-performance
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 30

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 31

 Functionality v. Usability
 Cost v. Robustness
 Efficiency v. Portability
 Rapid development v. Functionality
 Cost v. Reusability
 Backward Compatibility v. Readability

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 32

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 34

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 35

 A component is a replaceable part of a system that conforms to and


provides the realization of a set of interfaces.
 A component can be thought of as an implementation of a subsystem.
 UML definition of a component
 "A distributable piece of implementation of a system, including so(ware
code (source, binary, or executable), but also including business
documents, etc., in a human system."

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 36

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 37

 Classes represent logical abstractions.


They have attributes (data) and
operations (methods). Classes can be
combined to form programs.
 Components have operations that are
reachable only through interfaces.
Components can be combined to form
systems.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 38

19
User Interface

Manages advertisement
banners & sponsorships Manages Administers user
tournaments,promotions, accounts
applications

Tournament
Advertisement User Management

Adds games, styles,


and expert rating Services
formulas are described
by subsystem
Component
interfaces
Management
User Directory

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

 Subsystem interface: Set of fully typed UML


operations
 Specifies the interaction and information flow from and
to subsystem boundaries, but not inside the subsystem
 Refinement of service, should be well-defined and small
 Subsystem interfaces are defined during object design
 Application programmer’s interface (API)
 The API is the specification of the subsystem interface in
a specific programming language
 APIs are defined during implementation
 The terms subsystem interface and API are often
confused with each other
 The term API should not be used during system design
and object design, but only during implementation.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 40

20
 A package is a general-purpose mechanism for organizing
elements into groups.

 A node is a physical element that exists at run time and


provides a computational resource, e.g., a computer, a
smartphone, a router.
 Components may live on nodes.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 41

 Service provided by Notification Subsystem


 LookupChannel()
 SubscribeToChannel()
 SendNotice()
 UnscubscribeFromChannel()
 Subsystem Interface of Notification
Subsystem
 Set of fully typed UML operations
 Left as an Exercise
 API of Notification Subsystem
 Implementation in Java
 Left as an Exercise.
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 42

21
 Good design: The subsystem interface object
describes all the services of the subsystem
interface

 Subsystem Interface Object


 The set of public operations provided by a
subsystem

Subsystem Interface Objects can be realized with


the Façade pattern (=> lecture on design
patterns).

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 43

 An API is an interface that is realized by one or more


components.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 44

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 45

 Two major types of Layer relationships


 Layer A “depends on” Layer B (compile time dependency)
 Example: Build dependencies (make, ant, maven)

 Layer A “calls” Layer B (runtime dependency)


 Example: A web browser calls a web server

 Can the client and server layers run on the same machine?

 Yes, they are layers, not processor nodes


 Mapping of layers to processors is decided during the Software/hardware mapping!
 Partition relationship
 The subsystems have mutual knowledge about each other
 A calls services in B; B calls services in A (Peer-to-Peer)

 UML convention:
 Runtime dependencies are associations with dashed lines
 Compile time dependencies are associations with solid lines.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 46

23
Partition Layer
relationship Relationship
A:Subsystem „depends on“ Layer 1

B:Subsystem C:Subsystem D:Subsystem Layer 2

E:Subsystem F:Subsystem G:Subsystem Layer 3


Layer
Relationship
„calls“
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 47

User Interface

Tournament
Advertisement User Management

Component
Management
User Directory

Tournament
Session Statistics
Management

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 48

24
User Interface
Component
Management

Advertisement Tournament

Tournament
Statistics

Session User Management


Management

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 49

 Static pages from server


 All interaction requires communication with server

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 50

25
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 51

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 52

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 53

REQ1, REQ2,
REQ3 REQ3, REQ4
PROBLEM DOMAIN

(5) Device
(6) Photosensor
preferences
(7) Light
Subsystem-2
(3) Key

(1) Tenant (4) List of


Subsystem-1
valid keys
(3) Lock

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)

IN doc System OUT doc

1.b) User edits information stored in a repository


User System
System

Repository
User

2. Computer system controls the environment


(user not involved)

System Environment

3. Computer system intermediates between 3.a) System observes the environment and displays information
the user and the environment

User System Environment

User System Environment 3.b) System controls the environment as commanded by the user

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 User 55


System Environment

 An architectural style is system architecture


that recurs in many different applications.
 See:
 Mary Shaw and David Garlan, So3ware
architecture: perspec1ves on an emerging
discipline. Prentice Hall, 1996
 David Garlan and Mary Shaw, An Introduction
to Software Architecture. Carnegie Mellon
University, 1994 on course page

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 56

28
SUPPLEMENT

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 57

Abstraction
Stepwise refinement: decomposition
Modularity Modularization
Information hiding
Top-down versus Bottom-up
Cohesion, coupling

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 58

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.

 •Designers tend to design modules such that


they can be executed and/or compiled
separately and independently.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 59

 A complex problem is broken down into several manageable


pieces.
 Let P1 and P2 be the two problems
 Let E1 and E2 be the effort required to solve P1 & P2, resp.
 If C(P1) > C(P2), then E(P1) > E(P2)
 C: Complexity
 E: Effort
 If C(P1+P2) > C(P1) + C(P2), then E(P1+P2) > E(P1)+E(P2)
 It is easier to solve a complex problem when it is broken into
smaller pieces.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 60

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)

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 61

 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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 62

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 63

 The elements in a module are not related but simply


bundled together.
 Where does this type of cohesion come from?
 Sloppy maintenance
 Subroutinization

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 64

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;

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 65

 A module performs a number of actions, each with its own


entry point, with independent code for each action, all
performed on the same data structure.
 Essentially an implementation of an abstract data type.
 Example: Class in OO
 Module with Informational Cohesion

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 66

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 67

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 68

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 69

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.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 70

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).

 Is functional cohesion always good?


 There might be some occasions in which we have to choose another type
of cohesion instead of functional cohesion.
 In what case and why?
 Is data coupling always good?
 There might be some occasions in which we have to use common
coupling, i.e. global variables.
 In what case and why?
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 72

36
Management Aspects
 Preliminary design: transformation of
requirements into data and software
architecture.

 Detailed design: refinements to the architectural


representation that lead to detailed data
structure and algorithmic representations for
software

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 73

Technical Aspects
 Datadesign: transformation of the information domain
model created during analysis into the data structures.

 Architecturaldesign: definition of the relationship among


major structural components of the software.

 Proceduraldesign: transformation of structural


components into a procedural description of the
software.

 (User) Interfacedesign: establishment of the layout and


interaction mechanisms for human-machine interaction.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 74

37
 Select/Design data representation
 Concept of persistency
 Operation(behavior) > Data
 Operation = Data
 Operation < Data

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 75

 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."'

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 76

38
 Define algorithmic details.
 sequence, control, repetition.
 Notations:
 Graphical design notation
 Flowcharts,

 Nassi-Shneidermancharts

 Tabular design notation


 Decision tables

 Program design languages


 Structured English

 Pseudocode

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 77

 Step 1 Obtain background information


 Step 2 Define the semantics of the user
interface
 Step 3 Define the syntax and format of the
interface ( including choices of interaction style)
 Step 4 Choose the physical devices
 Step 5 Developing the software
 Step 6 Integrate and install the system
 Step 7 Provide on-site and product support

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 78

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 79

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 80

40
a.k.a. Tiered Software Architecture

User Interaction User Authentication Archiving

Control of Communicating alerts


Sensors and Devices about intrusion

User Interface Domain Logic Layer Technical Services


Layer (Business Rules) Layer

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 81

 Decomposed into groups of subtasks, each


of which is at a particular level of
abstraction.
 Each layer provides services to the next
higher level
 Common example 
 Network systems, E-commerce

 Agility
 Ease of development
 Performance
 Ease of deployment
 Suitable for Devops

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 82

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

 A producer/consumer computing architecture,


 server acts as the producer, providing services such as
application access, storage, file sharing, printer access, …
 client acts as the consumer

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 83

Simplifies reusability, exchangeability, and distribution

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 84

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,..

filter filter filter


pipe pipe

% ls folder-name | grep –v match-string | more

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 85

B,CMPS4131,Joe
B,CMPS3141,Joe 2A
A,CMPS4131,Ben
A,CMPS4131,Tadeo ???? 1B

 Goal: group and count CMPS4131 letter grades.

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 86

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

Pipe and filter is an architecture (not a design) pattern, why?

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 87

B,CMPS4131,Joe
B,CMPS3141,Joe 2A
A,CMPS4131,Ben grep CMPS4131 grades.csv | cut –f1 –d ‘,’ | sort | uniq -c 1B
A,CMPS4131,Tadeo

The pipe-and-filter architecture doesn’t


specify the design or implementation details
of the individual components (filters)!

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 88

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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 89

 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

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 90

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

3. Change your display Model


1. The user did something

user Controller 2. Change your state

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

View Model: array of numbers [ 14, 26, 31 ]

31
26 14
14 31
versus
Different Views for the same Model: 26

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 92

46
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 93

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 94

47
Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 95

 Architecture and design


 Components and interfaces: understand, communicate, reuse
 Manage complexity: modularity and separation of concerns
 Process: allow effort estimation and progress monitoring

Copyright 2023, Ivan Marsiac. Slides modified for UB-CMPS4131 96

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 2

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

 Functional models represent system behavior


 Structural models represent system objects and
their relationships:
 People
 Places
 Things
 Create a conceptual model and evolve it into a
design model using
 CRC cards
 Class diagrams
 Object diagrams

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 4

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 5

Main goal: to discover the key data


contained in the problem domain and to
build a structural model of the objects

Structural
Modeling

Solution Domain
Problem Domain

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 6

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 7

Step 4. Draw a system sequence diagram for


each use case scenario.
Step 5. Produce a domain model showing the
concepts, attributes and associations
in the problem domain of the system.
Step 6. Write a contract for each system
operation.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 8

4
Produce a domain model showing the
concepts, attributes, and associations
in the problem domain of the system.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 9

 Models used mainly for requirements


 Use case diagram shows a set of use cases and actors, and their
relationships.
 Models used mainly for systems architecture
 Component diagram shows the organization and dependencies
among a set of components.
 Deployment diagram shows the configuration of processing nodes
and the components that live on them.
 Models used mainly for program design
 Class diagram shows a set of classes, interfaces, and
collaborations with their relationships.
 Object diagram or sequence diagram show a set of objects and
their relationships.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 10

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 11

 A domain model is a system of abstractions


 The model can then be used to solve problems related to that
domain.
 The domain model is a representation of meaningful real-world
concepts pertinent to the domain that need to be modelled in
software.
 The concepts include the data involved in the business and rules the
business uses in relation to that data.
 A domain model is generally implemented as an object model within
a layer that uses a lower-level layer for persistence and "publishes"
an API to a higher-level layer to gain access to the data and
behavior of the model.
 In UML, a class diagram can be used to represent the domain model.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 12

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 13

 Visual representation of conceptual classes.


 Associations and relationships between concepts
(e.g Payment PAYS-FOR Sales).
 Attributes for information content (e.g. Sale
records DATE and TIME).
 Does not include operations / functions.
 Does not describe software classes.
 Does not describe software responsibilities.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 14

7
.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 15

 A concept is an abstraction of a thing,


a person, or an idea. It is represented
by a rectangle.
 An attribute is a characteristic of a
concept which may have a value.
Attribute names appear in the lower
compartment of the concept rectangle.
 An association is a significant connection
between concepts. It is represented by a
line connecting a pair of concepts.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 16

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

A recommended flow for domain modeling is shown


below in sequential order:
1. Prepare problem statement for the system being
developed.
2. Identify classes and objects.
3. Develop data dictionary.
4. Identify association between classes.
5. Identify attributes of classes and association classes.
6. Structure objects using inheritance.
7. Verify access paths for likely queries.
8. Iterate and refine the model.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 18

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 19

 Given a real-life system, how do you decide what


classes to use?
Step 1. Identify a set of candidate classes that represent
the system design.
 What terms do the users and implementers use to
describe the system? These terms are candidates for
classes.
 Is each candidate class crisply defined?
 For each class, what is its set of responsibilities? Are the
responsibilities evenly balanced among the classes?
 What attributes and methods does each class need to
carry out its responsibilities?

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 20

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 21

A good design is often a combination of


application classes and solution classes.
 Application classes represent application
concepts.
 Noun identification is an effective technique to
generate candidate application classes.
 Solution classes represent system concepts,
e.g., user interface objects, databases, etc.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 22

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 23

 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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 24

12
To distinguish different object types
in a model we can use the
UML Stereotype mechanism

Year Button
ChangeDate

Month
LCDDisplay

Day

Entity Objects Control Object Boundary Objects


Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 25

 UML provides the stereotype mechanism to


introduce new types of modeling elements
 A stereotype is drawn as a name enclosed by angled double-quotes
(“guillemets”) (<<, >>) and placed before the name of a UML element
(class, method, attribute, ….)
 Notation: <<String>>Name

<<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

 One can use icons to identify a stereotype


 When the stereotype is applied to a UML model
element, the icon is displayed beside or above the
name

Year ChangeDate Button WatchUser

Entity Object Control Object Boundary Object Actor

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 28

14
Library Example
Student Registration Example

The library contains books and journals. It may have


several copies of a given book. Some of the books are
reserved for short-term loans only. All others may be
borrowed by any library member for three weeks.
Members of the library can normally borrow up to six
items at a time, but members of staff may borrow up to
12 items at one 5me. Only members of staff may borrow
journals.
The system must keep track of when books and journals
are borrowed and returned, and enforce the rules.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 30

15
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 31

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 32

16
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 33

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 34

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 35

Concepts (Objects)

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 36

18
Attributes describe concepts.

Concept Student Professor Section

Attributes: studentIdentifier professorIdentifier number

studentName professorName meetingTime

studentAddress professorAddress meetingPlace

major title maximum


classLevel NumberOf
Students

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 37

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 38

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

studentName Louella Fernbee Mortimer Snow


studentAddress 123 Any St. 456 Some St.

major CIS CS
classLevel Junior Sophomore

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 39

FIGURE 5.7

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 40

20
 Always model associations explicitly;
never use an attribute to imply an
association.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 41

There are instances of associations as well


as instances of concepts.
Association: Enrolled In
Instance: studentIdentifier = 41068 associated with
sectionNumber = CIS-4-01
FIGURE 5.6

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 42

21
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 43

 Having three types of object leads to models


that are more resilient to change
 The interface of a system changes more likely
than the control
 The way the system is controlled changes more
likely than entities in the application domain
 Object types originated in Smalltalk:
 Model, View, Controller (MVC)
Model <-> Entity Object
View <-> Boundary Object
Controller <-> Control Object
 Next topic: Finding objects.
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 44

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

 Textual analysis of use-case information


 Nouns suggest classes
 Verbs suggest operations
 Creates a rough first cut to provide an object list
 Brainstorming—people offering ideas
 Initial list of classes (objects) is developed
 Attributes, operations and relationships to other
classes can be assigned in a second round

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 46

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 47

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".

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 48

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

Customer Flow of events:


 The customer enters the store
store
? to buy a toy.
toy It has to be a
toy that his daughter likes and
enter() it must cost less than 50 Euro.
He tries a videogame,
videogame which
daughter
age uses a data glove and a head-
mounted display. He likes it.
suitable
An assistant helps him. The
*Toy suitability of the game depends
toy
price on the age of the child. His
buy()
buy() daughter is only 3 years old.
like()
The assistant recommends another
toy namely a boardgame.
type of toy, boardgame
videogame boardgame
The customer buy the game and
leaves the store
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 50

25
 Syntactical investigation with Abbot‘s technique:
 Flow of events in use cases
 Problem statement

 Use other knowledge sources:


 Application knowledge: End users and experts know
the abstractions of the application domain
 Solution knowledge: Abstractions in the solution
domain
 General world knowledge: Your generic knowledge and
intution

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 51

1. Formulate a few scenarios with help from


an end user or application domain expert
2. Extract the use cases from the scenarios,
with the help of an application domain
expert
3. Then proceed in parallel with the following:
 Analyse the flow of events in each use case
using Abbot's textual analysis technique
 Generate the UML class diagram.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 52

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

 The client and the end user are usually not


interested in class diagrams
 Clients focus more on project management issues
 End users are more interested in the
functionality of the system.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 54

27
UML Notation

A static model that shows classes and their


relationships to one another
 Elements
 Classes
 Objects within the system (a person, place or thing)
 Stores and manages information in the system and contains:
 Attributes—characteristics of the class
 Operations—activities the class can perform
 Relationships—the associations between classes
 Depicted as lines between classes
 Multiplicity indicates how many of one object is/are associated
with other objects

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 56

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 57

 A “Hello, World!” Applet  A “Hello, World!” Class

Example from: BRJ

 The HelloWorld Class

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 58

29
 Describe how classes relate to one another

 A dependency is a semantic relationship between two things in which a change


to one may effect the semantics of the other.

 A generalization is a relationship is which objects of the specialized element


(child) are substitutable for objects of the generalized element (parent).

 A realization is a semantic relationship between classifiers, wherein one classifier


specifies a contract that another classifier guarantees to carry out.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 59

 Denotes associations between classes


 Depicted with a line labeled with the name of
the relationship
 May be directional (depicted with a triangle;
e.g., a patient schedules an appointment)
 Classes may be related to themselves (e.g.,
employees and managers who may be
members of the same class)
 Multiplicity indicates how many of one class
are related to another class

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 60

30
 Note that the Applet and
Graphics classes are shown
elided, i.e., just the name
is shown, not the
attributes or operations.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 61

 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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 63

 An association is a structural relationship that describes a set of links, a


link being a connection among objects.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 64

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

 Common in many-to-many relationships


 Used when attributes about the relationship
between two classes needs to be recorded
 Students are related to courses; a Grade class
provides an attribute to describe this relationship
 Illnesses are related to symptoms; a Treatment
class provides an attribute to describe this
relationship

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 66

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 67

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 68

34
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 69

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 70

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)

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 71

 Class diagrams with instantiated classes


 Example: instead of a Doctor class, create an
actual doctor, say Dr. Smith
 Place values into each attribute
 Used to discover additional attributes,
relationships and/or operations or those that
are misplaced

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 72

36
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 73

 Analyst presents to developers & users


 Walks through the model
 Provides explanations & reasoning behind each
class
 Rules
1. Each CRC card is associated with a class
2. Responsibilities on the front of the card are
included as operations on the class diagram
3. Collaborators on the front of the card imply a
relationship on the back of the card
4. Attributes on the back of the card are listed as
attributes on the class diagram
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 74

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 75

Supplement Example

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 76

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 77

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 78

39
Step 1: Identifying the boundary concepts

Boundary concepts Concept 3


Concept 1
Actor C
Actor A

Step 2: Identifying the internal concepts


Concept 2
Concept 4
Actor B Actor D
Concept 3
Concept 1
Actor C
Concept 6
Actor A
Concept 5

Internal
Concept 2 concepts
Concept 4
Actor B Actor D

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 79

Use Case UC-1: Unlock

Related Requirements: REQ1, REQ3, REQ4, and REQ5 stated in Table 2-1

Initiating Actor: Any of: Tenant, Landlord

Actor’s Goal: To disarm the lock and enter, and get space lighted up automatically.

Participating Actors: LockDevice, LightSwitch, Timer

• The set of valid keys stored in the system database is non-empty.


Preconditions: • The system displays the menu of available functions; at the door keypad the menu
choices are “Lock” and “Unlock.”
Postconditions: The auto-lock timer has started countdown from autoLockInterval.

Flow of Events for Main Success Scenario:

 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

Operate the lock device to armed/disarmed positions. D LockOperator

Operate the light switch to turn the light on/off. D LightOperator

Operate the alarm bell to signal possible break-ins. D AlarmOperator

Block the input to deny more attempts if too many unsuccessful attempts. D Controller

Log all interactions with the system in persistent storage. D Logger

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 81

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

Domain concepts for subsystem #1 of safe home access

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 82

41
«boundary»
HouseholdDeviceOperator

«boundary» «boundary» «boundary» «boundary»


LockOperator LightOperator MusicPlayerOperator AlarmOperator

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 83

Associations: who needs to work together, not how they work together
Domain model for UC-1: Unlock Concept pair | Association description | Association name

«entity» retrieves valid keys «entity»


KeyChecker KeyStorage

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

“Reading direction arrow.”


Resident Has no meaning; it only helps reading
LightSwitch
the association label, and is often left out.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 84

42
«boundary»
HouseholdDeviceOperator

deviceStatus

«boundary» «boundary» «boundary» «boundary»


LockOperator LightOperator MusicPlayerOperator AlarmOperator
autoLockInterval
holdOpenInterval
asks-illumination provides-play- notifies-members
acceptingInterval
schedule

«boundary» «entity» «entity»


IlluminationDetector PlayList NotificationList

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 85

Use Case UC-5: Inspect Access History


Related Requirements: REQ8 and REQ9 stated in Table 2-1

Initiating Actor: Any of: Tenant, Landlord


Actor’s Goal: To examine the access history for a particular door.

Participating Actors: Database, Landlord

Preconditions: Tenant/Landlord is currently logged in the system and is shown a hyperlink “View Access History.”
Postconditions: None.

Flow of Events for Main Success Scenario:


 1. Tenant/Landlord clicks the hyperlink “View Access History”

 2. System prompts for the search criteria (e.g., time frame, door location, actor role, event type, etc.) or “Show all”

 3. Tenant/Landlord specifies the search criteria and submits


System prepares a database query that best matches the actor’s search criteria and retrieves the records from
 4.
the Database
 5. Database returns the matching records
System (a) additionally filters the retrieved records to match the actor’s search criteria; (b) renders the
6.
 remaining records for display; and (c) shows the result for Tenant/Landlord’s consideration
Tenant/Landlord browses, selects “interesting” records (if any), and requests further investigation (with an
 7.
accompanying complaint description)
System (a) displays only the selected records and confirms the request; (b) archives the request in the Database
8. and assigns it a tracking number; (c) notifies Landlord about the request; and (d) informs Tenant/Landlord about

the tracking number
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 86

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

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 87

Concept pair Association description Association name

Controller passes requests to Page Maker and receives back


Controller  Page Maker conveys requests
pages prepared for displaying

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

Controller passes a list of “interesting” records and complaint


Controller  Archiver description to Archiver, which assigns the tracking number and conveys requests
creates Investigation Request

Archiver  Investigation
Archiver generates Investigation Request generates
Request

Archiver  Database Archiver requests Database Connection to store investigation


requests save
Connection requests into the database
Archiver requests Notifier to notify Landlord about investigation
Archiver  Notifier requests notify
requests

Associations (describe who needs to work together and why, not how they work together).

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 88

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.

records list List of “interesting” records selected for further investigation.


Investigation
complaint description Describes the actor’s suspicions about the selected access records.
Request
tracking number Allows tracking of the investigation status.

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 89

Domain model for UC-5: Inspect Access History

«control» «entity» «entity»


Controller Archiver InvestigationRequest
conveys-requests generates
«boundary» currentTrackNum recordsList
SearchRequest complaintDescr
receives trackingNum
userID
searchParams uses
conveys requests

posts «boundary»
Notifier
«boundary»
InterfacePage saves-data-to
contactInfo
Landlord
conveys-requests
prepares

«entity» «boundary»
PageMaker DatabaseConnection
provides-data
Resident Database

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 90

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>

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 91

Mapping: System requirements to Use cases


UC1: Unlock
UC2: Lock
UC3: AddUser
REQ1: Keep door locked and auto-lock UC4: RemoveUser
REQ2: Lock when “LOCK” pressed UC5: InspectAccessHistory
REQ3: Unlock when valid key provided UC6: SetDevicePrefs
REQ4: Allow mistakes but prevent dictionary attacks UC7: AuthenticateUser
REQ5: Maintain a history log UC8: Login
REQ6: Adding/removing users at runtime
REQ7: Configuring the device activation preferences
REQ8: Inspecting the access history
REQ9: Filing inquiries Req’t PW UC1 UC2 UC3 UC4 UC5 UC6 UC7 UC8

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

Create a domain model one use case at a time.


Then, merge them to form a complete
domain model for the entire system.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 94

47
Write a contract for each system operation.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 95

 Contracts express any important conditions


about the attributes in the domain model. In
addition to attributes, contract may include
facts about forming or breaking relations
between concepts and the time-points at
which instances of concepts are created or
destroyed.
 You can think of a software contract as
equivalent to a rental contract, which spells
out the condition of an item prior to renting,
and will spell out its condition subsequent to
renting.
Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 96

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 97

A system operation is an operation which the


system carries out in response
to a system input.
The system input and the system operation
have the same name.

This relationship will be an important link


between the system analysis models and
the system design models.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 98

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.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 99

 What instances of concepts must be


created or deleted?
 What attributes have their values
modified? To what new values?
 Which instances of associations must be
added or deleted?

Use the past tense and the passive voice.

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 100

50
FIGURE 5.28

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 101

FIGURE 5.27

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 102

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

• numOfAttempts = 0, if the entered Key  Valid keys


Postconditions
• current instance of the Key object is archived and destroyed

Operation Lock
Preconditions
None (that is, none worth mentioning)

• lockStatus = “armed”, and


Postconditions
• lightStatus remains unchanged (see text for discussion)

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 103

What lies ahead to Report #2……….

Design
System Sequence Diagram Sequence Diagram

Controller : Checker : KeyStorage : LockCtrl

User
«initiating actor»
ystem
: System
Timer
«offstage actor»
checkKey()
sk := getNext()
select function(“unlock")

prompt for the key


alt val != null setOpen(true)
enter key
verify key

signal: valid key, lock open [else] val == null : setLit(true)


open the lock,
turn on the light

start ("duration“)

Copyright 2022, Ivan Marsiac. Slides modified for UB-CMPS4131 104

52

You might also like