You are on page 1of 62

Unified Modeling Language (UML)

Prepared by Tevfik Bultan


UML (Unified Modeling Language)
• Combines several visual specification techniques
– class diagrams
– sequence diagrams
• Based on object oriented principles and concepts
– encapsulation, abstraction
– classes, objects
• Semi-formal
– Precise syntax but no formal semantics
• There are tools which support UML
– Rational Rose
UML References
• There are lots of books on UML. The ones I used are:
– “Using UML,” Perdita Stevens
– “UML Distilled,” Martin Fowler
• The examples I use in this lecture are from this book
– “UML Explained,” Kendall Scott
– “UML User Guide,” Grady Booch, James Rumbaugh, Ivar
Jacobson
UML

• Functionality
– Use-case diagrams
• Decomposition
– Class diagrams (class structure)
– Package diagrams, Deployment diagrams (architecture)
• Behavior
– State diagrams, Activity diagrams
• Communication
– Sequence diagrams, Collaboration diagrams
Use Cases and Use Case Diagrams

• References
– “Getting started: Using use cases to capture requirements”, James
Rumbaugh, 1994
– “Using UML”, Perdita Stevens, Rob Pooley, 2000

• Use cases are used in the requirements specification phase

• Use cases document the behavior of the system from the users’ point
of view.
– By user we mean anything external to the system
– It can be another software system interacting with the software
system being specified
Actors in Use Cases
• An actor is a role played by an outside entity that interacts directly
with the system

– An actor can be a human, or a machine or a program

– Actors are shown as stick figures in use case diagrams

Librarian
Use Cases
• A use case describes the possible sequences of interactions among the
system and one or more actors in response to some initial stimulus by
one of the actors
– Each way of using the system is called a use case
– A use case is not a single scenario but rather a description of a set
of potential scenarios
– For example: Installing a Database, Adding a New User to the
Database
– Individual use cases are shown as named ovals in use case
diagrams

Installing
a Database
Use Cases
• A use case involves a sequence of interactions between the initiator
and the system, possibly involving other actors.

• In a use case, the system is considered as a black-box


– We are only interested in externally visible behavior

• Description of a use case should include events exchanged between


objects and the operations performed by the system that are visible to
actors
Use Cases
• To define a use case, group all transactions that are similar in nature

• A typical use case might include a main case, with alternatives taken
in various combinations and including all possible exceptions that can
arise in handling them

– Use case for a bank: Performing a Transaction at the Counter


• Subcases could include Making Deposits, Making
Withdrawals, etc., together with exceptions such as
Overdrawn or Account Closed

– Apply for a Loan could be a separate use case since it is likely to


involve very different interactions
Combining Use Cases
• A use case extends another use case when it embeds new behavior
into a complete base case

– Check Baggage extends the base case Check in for Flight

– You do not have to check baggage to check in for flight.


Combining Use Cases
• A use case uses another use case when it embeds a subsequence as a
necessary part of a larger case

– uses relationship permits the same behavior to be embedded in


many otherwise unrelated use cases

– For example Check in for Flight use case uses Assign Seat use
case

• In some of the references this relationship is called includes instead of


uses
Combining Use Cases
• The difference between extends and uses:

– In the extends the extended use case is a valid use case by itself

– In the uses the use case which is using the other use case is not
complete without it
Use Case Diagrams: Combining Use Cases

<<uses>> Check in
Assign Seat for Flight

<<extends>>
<<extends>>

Upgrade
Check use case
Seat
Flight Attendant Baggage

actor

Customer
Defining Use Cases
• Identify the boundary of the application, identify the objects outside
the boundary that interact with the system

• Classify the objects by the roles they play, each role defines an actor

• Each fundamentally different way an actor uses the system is a use


case
Defining Use Cases
• Specify some specific scenarios for each use case
– plug in parameters if necessary

• Determine the interaction sequences


– identify the event that initiates the use case
– determine if there are preconditions that must be true before the
use case can begin
– determine the conclusion
Defining Use Cases
• Write a prose description of the use case

• Consider all the exceptions that can occur and how they affect the use
case

• Look for common fragments among different use cases and factor
them out into base cases and additions
Documenting Use Cases
Use case: Place Order
Actors: Costumer
Precondition: A valid user has logged into the system
Flow of Events:
1. The use case begins when the customer selects Place Order
2. The customer enters his or her name and address
3. If the customer enters only the zip code, the system supplies the city and state
4. The customer enters product codes for products to be ordered
5. For each product code entered
a) the system supplies a product description and price
b) the system adds the price of the item to the total
end loop
6. The customer enters credit card payment information
7. The customer selects Submit
8. The system verifies the information [Exception: Information Incorrect], saves the order as pending, and forwards
payment information to the accounting system.
9. When payment is confirmed [Exception: Payment not Confirmed], the order is marked confirmed, an order ID is
returned to the customer, and the use case terminates
Exceptions:
Payment not Confirmed: the system will prompt the customer to correct payment information or cancel. If the customer
chooses to correct the information, go back to step 6 in the Basic Path. If the customer chooses to cancel, the use case
terminates.
Information Incorrect: If any information is incorrect, the system prompts the customer to correct it.
Postcondition: If the order was not canceled, it is saved in the system and marked confirmed
Documenting Use Cases
Flow of Events:
Basic Path:
1. The use case begins when the customer selects Place Order
2. The customer enters his or her name and address
3. While the customer enters product codes
a) the system supplies a product description and price
b) the system adds the price of the item to the total
end loop
6. The customer enters credit card payment information
7. The customer selects Submit
8. The system verifies the information [Exception: Information Incorrect], saves the order as pending, and
forwards payment information to the accounting system.
9. When payment is confirmed [Exception: payment not confirmed], the order is marked confirmed, an order ID is
returned to the customer, and the use case terminates
Alternative Paths:
– At any time before selecting submit, the customer can select Cancel. The order is not saved and the use case
ends
– In step 6, if any information is incorrect, the system prompts the customer to correct the information
– In step 7, if payment is not confirmed, the system prompts the customer to correct payment information or
cancel. If the customer chooses to correct the information, go back to step 4 in the Basic Path. If the
customer chooses to cancel, the use case ends.
Online Human Resources (HR) System
system
Online HR System boundary

Locate
Employee

Manager
Update Employee
Profile

[ current month is October]


Update Benefits

Employee Healthcare Plan System

Access Travel
System
[read only access]

Access Pay
Records
Employee Account Insurance Plan
Database System
Online HR System
Use case: Update Benefits
Actors: Employee, Employee Account Database, Healthcare Plan System, Insurance Plan
System
Precondition: Employee has logged on to the system and selected “update benefits” option
Flow of Events:
Basic Path:
1. System retrieves employee account from Employee Account Database
2. System asks employee to select medical plan type; uses Update Medical Plan
3. System asks employee to select dental plan type; uses Update Dental Plan
...

Alternative Paths:
If health plan is not available in the Employee’s area the employee is informed and
asked to select another plan
Online HR System

Update
Dental Plan Update
Update Insurance Plan
Medical Plan
<<uses>> <<uses>>
<<uses>>
Update Benefits
Extension Points extension point name
Benefits Options: after extension location
required enrollments
Employee
<<extends>>(Benefits Options)
[employee requests
<<extends>> (Benefits Options) stock purchase option]
[employee requests
reimbursement option]
Select Stock
Purchase
Select Reimbursement
for Healthcare
Generalization in use case diagrams

Validate
Customer User

Check Retinal
Password Scan
Corporate
Individual Customer
Customer
UML Class Diagrams
• Class diagram describes
– Types of objects in the system
– Static relationships among them

• Two principal kinds of static relationships


– Associations between classes
– Subtype relationships between classes

• Class descriptions show


– Attributes
– Operations

• Class diagrams can also show constraints on associations


UML Class Diagrams
• Class diagrams can be used at different stages of development
– For requirements specification, for design specification, and for
implementation

• In requirements specification class diagrams can be used to model real


world objects or concepts

• In design specification it can be used to specify interfaces and classes


that will be implemented in an object oriented program

• In implementation they can be used to show the architecture of the


software by showing the relationships among different classes
Classes
• A class is represented as a three-part box
• Class Name
• Attributes
– At conceptual level it is a piece of information associated with the
class that can be accessed and possibly modified
– Corresponds to a field at the implementation level
– Difference from association: navigability is from class to attribute
(not both ways as in association)
• Operations
– The processes the class can carry out (methods at implementation
level)
– Basic operations (such as getValue) on attributes can be omitted
(they can be inferred)
Classes
Attribute syntax: visibility name: type = defaultValue

Operation syntax: visibility name(parameter-list): return-type-expression {property string}

property values that apply to this operation

Class Name Customer


name
Attributes address

Operations +creditRating():String

Visibility:
public + (default) any outside class with visibility to the given class can use the feature
protected # any descendant of the class can use the feature
private – only the class itself can use the feature

For abstract classes, class name is written in italic: Customer


Associations Order
dateReceived
Associations are shown as lines between classes isPrepaid
• An association shows a relationship between instances of number: String
two classes price: Money
– Each association has two roles (one for each direction) dispatch()
– A role can be explicitly named with a label close()
– Role syntax: 1
• visibility name: type = defaultValue
– Roles have multiplicity showing how many objects Association
participate in the relationship
Role Name Multiplicity:
– Associations can have multiplicities
1 or more
• A fixed value (such as 1 or 3)
Ordered
• Many denoted by * (unlimited number) Product 1..*
• A range of values 0..1 or 3..*
Product Order
• A set of values 2,4,8
quantity: Int
price: Money
isSatisfied: Bool
Generalization
Customer
• Sharing mechanism based on a hierarchical name
relationship between classes address
– Subtype is a specialization of the
creditRating():String
supertype
– Subtype can be substituted for the indicates
generalization
supertype
– Subtype inherits the interface
Corporate Personal
– Subtype inherits the operations Customer Customer
contactName
creditRating creditCardNumber
creditLimit

remind()
billForMonth(Int)
Constraints
• Represent further restrictions on associations or classes
• They are stated inside braces {} and there is no formal syntax for
them in UML
• Object Constraint Language (OCL) is a formal language for
specifying constraints

Order Customer
dateReceived
isPrepaid 1..* 1 name
number: String address
price: Money
creditRating():String
dispatch() Constraint
close() for order class

{If Order.customer.creditRating
is “poor”, then Order.isPrepaid
must be true}
Example Class Diagram
Order Customer
dateReceived 1..* 1 name
isPrepaid address
number: String
price: Money creditRating():String
dispatch() Constraint indicates
close() for order class generalization
1

{If Order.customer.creditRating Corporate Personal


is “poor”, then Order.isPrepaid Customer Customer
must be true} contactName
creditRating creditCardNumber
Ordered
Product creditLimit
1..*

Product Order remind()


billForMonth(Int)
quantity: Int 1..* 1 {creditRating()=“poor”}
Product
price: Money 1..* indicates that credit
isSatisfied: Bool Sales
rating is always
Rep 0..1
set to poor for a
Employee Personal Customer
Aggregation and Composition
• Aggregation is a part-of relationship
• Composition is also a part-of relationship, but part and whole live and
die together

Order

1 1
shows shows
aggregation 1 composition
1 1
Shipping Billing
Information Information

1..*
Book
Qualified Associations
• Association can be keyed by the value of the qualifier

Order qualifier
dateRecieved
isPrepaid Product Order
number: String 0..1 quantity: Int
Product
price: Money Ordered price: Money
dispatch() Product isSatisfied: Bool
close()
Association Classes
• Adds attributes and operations to an association
– Allows exactly one instance of the association class between any
two objects
– Can use an actual class instead, if you need more

0..* 1..*
Company Person
employer employee

Job
description
dateHired
salary
Sequence Diagrams
• A sequence diagram shows a particular sequence of messages
exchanged between a number of objects

• Sequence diagrams also show behavior by showing the ordering of


message exchange

• A sequence diagram shows one particular communication sequence in


one run of the system
– it is not characterizing all possible runs
Sequence Diagrams
• Sequence diagrams can be used in conjunction with use-cases at the
requirements phase, or at the design phase they can be used to show
the system’s behavior that corresponds to a use-case

• Sequence diagrams can be used to generate test cases for the software
product

• Sequence diagrams are similar to MSCs (Message Sequence Charts)


which are a part of SDL and have formal semantics
Components of Sequence Diagrams

• Object (an instance of a class)


– shown as a box at the top
of a vertical dashed line instance name
– instance syntax can be omitted
:OrderEntryWindow (means anonymous
instanceName:ClassName instance)

• Lifeline Object
– dashed line, represents
time flow

Lifeline
Components of Sequence Diagrams
• Messages
– communication between :ProductOrder :StockItem
objects
– method calls at the Message
implementation level check()
needsToReorder()
• Special message types
– self-delegation
Self-delegation
– return
• show returns only if it
adds to clarity Return
– <<create>>
– <<destroy>>
Components of Sequence Diagrams
• Two kinds of control
information: :Order :ProductOrder :StockItem

– message conditions *prepare()


check()
• message is sent only if Iteration
the condition is true
[check=“true”]
message remove()
– iteration marker: * condition
• message sent to
multiple receiver
objects
Example Sequence Diagram

:OrderEntryWindow :Order :ProductOrder :StockItem

prepare()
*prepare()
check()

[check=“true”]
remove()

needsToReorder()

[needsToReorder=“true”]
<<create>>
:ReorderItem

[check=“true”]
<<create>> :DeliveryItem
Sequence diagrams
• Show conditional behavior on separate diagrams to keep them
understandable
– for example for a use case you can give the basic path as one
sequence diagram and have separate sequence diagrams for
alternative paths or exceptions

• Use sequence diagrams to show the behavior of several objects within


a use case
– use a state diagram when you want to show the behavior of an
object across many use cases
Sequence Diagrams
• Focus of control (or
activation) can be shown :Order :ProductOrder :StockItem
in sequence diagrams as a
thin rectangle put on top
*prepare()
of the lifeline of an object check()
• Shows the period of time Iteration

during which the given [check=“true”]


object is in control of the message remove()
flow condition
• It is optional to use focus
of control rectangles in a
sequence diagram
– use it when it adds to
focus of control
clarity or activation

lifeline
Collaboration Diagrams

• Collaboration diagrams show a particular sequence of messages


exchanged between a number of objects
– this is what sequence diagrams do too!

• Use sequence diagrams to model flows of control by time ordering


– sequence diagrams can be better for demonstrating the ordering of
the messages
– sequence diagrams are not suitable for complex iteration and
branching

• Use collaboration diagrams to model flows of control by organization


– collaboration diagrams are good at showing the static connections
among the objects while demonstrating a particular sequence of
messages at the same time
Example Sequence Diagram

:OrderEntryWindow :Order :ProductOrder :StockItem

prepare()
*prepare()
check()

[check=“true”]
remove()

needsToReorder()

[needsToReorder=“true”]
<<create>>
:ReorderItem

[check=“true”]
<<create>> :DeliveryItem
Corresponding Collaboration Diagram
object
:OrderEntryWindow

1:prepare() message
link sequence number

:Order

1.1.2.1:needsToReorder()
1.1:*prepare()

:ProductOrder :StockItem

1.1.1:check()
1.1.2:[check==true]remove() 1.1.2.2:new

1.1.3:[check==true]new :DeliveryItem

:ReorderItem
State Diagrams
• State diagrams are used to show possible states a single object can get
into
– shows states of an object

• How object changes state in response to events


– shows transitions between states

• UML state diagrams are a variation of Statecharts


– Statecharts are hierarchical state machines

• Statecharts have formal semantics


State Diagrams: States
• States are represented as rounded boxes which contain:
– the state name
– and the following optional fields
• entry and exit actions: entry and exit actions are executed
whenever the state is entered or exited, respectively
• internal transitions: internal transitions do not activate the
entry and exit actions (different than self-transitions which
activate the entry and exit actions).
• activities: Typically, once the system enters a state it sits idle
until an event triggers a transition. Activities help you to
model situations where while in a state, the object does some
work that will continue until it is interrupted by an event
• deferred events: If an event does not trigger a transition in a
state, it is lost. In situations where you want to save an event
until it triggers a transition, use deferred events
State Diagrams: States

Tracking
entry action
entry / setMode(on Track)
exit action exit / setMode(off Track)
internal transition newTarget / tracker.Acquire()
do / followTarget
activity selfTest / defer
deferred event

Note that, “entry”, “exit”, “do”, and “defer” are keywords


State Diagrams: Transitions
• Transitions
– source state and target state: shown by the arrow representing
the transition
– trigger event: the event that makes the transition fire
– guard condition: a boolean expression that is evaluated when the
trigger event occurs, the transition can fire only if the guard
condition evaluates to true
– action: an executable atomic computation that can directly act on
the object that owns the state machine or indirectly on other
objects that are visible to the object
– initial and final states: shown as filled black circle and a filled
black circle surrounded by an unfilled circle, respectively
source state target state
trigger-event[guard-condition]/action
State Diagrams

shows the initial (default) state

/ getFirstItem

getNextItem Checking
[not all items checked]
do / checkItem

cancelled

shows the final state


State Diagram Example: States of an Order object

/ getFirstItem

getNextItem Checking [all items checked and Dispatching


[not all items checked] all items available]
do/checkIte do/initiate
m Delivery
itemReceived
[all items available]
[all items checked and
some items not in stock]
cancelled

itemsReceived
[some items not in stock]
cancelled
Waiting Delivered

cancelled

Cancelled
Active is a superstate
State Diagrams: Superstates with substates Checking,
Waiting and Dispatching

/ getFirstItem Active

getNextItem Checking [all items checked and Dispatching


[not all items checked] all items available]
do/checkIte do/initiate
m Delivery
itemReceived
[all items checked and [all items available]
some items not in stock]

itemsReceived
[some items not in stock]
Waiting

cancelled

Cancelled Delivered
State Diagrams: Concurrent states
• Payment authorization is done concurrently with the order processing

Authorizing
[payment not OK]
do/check Rejected
Payment

[payment OK]

Authorized

Delivered
State Diagrams: Concurrent States

cancelled

Waiting
Cancelled

Checking Dispatching

Delivered

Authorizing Authorized

this transition
can only be taken
after both concurrent
states reach their
final states
[payment not OK] Rejected
State Diagrams
• Good at describing behavior of an object across several use-cases

• Use them to show the behavior of a single object not many objects
– for many objects use interaction diagrams

• Do not try to draw state diagrams for every class in the system, use
them to show interesting behavior and increase understanding
Activity Diagrams
• Activity diagrams show the flow among activities and actions
associated with a given object using:
– activity and action states
– transitions
– branches
– merges
– forks
– joins

• Activity diagrams are derived from SDL state diagrams, SDL state
diagrams have formal semantics
Activity Diagrams
• Activity
– represents a task that has to be performed, a non-atomic execution
within a state machine
– from an implementation perspective it can represent a method

• Action
– an atomic computation that changes the state of the system or
returns a value
Activity Diagrams
• When an activity or action of a initial state
state is completed the control
passes immediately to the next
action or activity state
Receive
Supply
action or
• Transitions can have guard activity states
transition

conditions
Choose Outstanding
Order Item
• Multiple trigger symbol * is
used to show iteration * for each chosen
order item

Assign Goods
in Order
Activity Diagrams: Branches
• Conditional branches
– correspond to if-then-else or switch
statements at the implementation level
• a branch is shown as a diamond
Authorize
• a branch can have one incoming transition
guard Payment
and two or more outgoing expressions
• the guard conditions on different outgoing
transitions should not overlap to prevent branch
nondeterminism [succeeded]
• guard conditions on different outgoing
transitions should cover all the possibilities
so that the control flow does not get stuck at [failed]
the branch

Dispatch Order Cancel Order


Activity Diagrams: Forks and Joins
• Forks and joins are used to model
concurrent execution paths
• Allows parallelism and Receive Order
synchronization
fork
– forks create concurrent threads
– joins merge different threads
– both allow synchronization
Authorize Check Order
Payment Items

two threads are executing


concurrently

join
Dispatch
Order
Finance Order Stock
Processing Manager
ReceiveSupply
Receive Order

*for each
order item Choose Outstanding vertical lines
Order Items are used to separate
Authorize Check Order
“swimlanes”
Payment Item
* for each to show which
[in stock] chosen activities are handled
[failed] order item by which part of the
Assign to Order system
Assign to
Cancel Order
[succeeded]
Order

[need to reorder]

Reorder
item
[all outstanding order
items filled]

[stock assigned to all order items Add Remainder


and payment authorized] to Stock
Dispatch
Order
How do they all fit together?
• Requirements analysis and specification
– use-cases, use-case diagrams
• Design
– Class diagrams can be used for showing the decomposition and the
architecture of the design
– Activity diagrams can be used to specify behaviors described in
use cases
– State diagrams are used to specify behavior of individual objects
– Sequence and collaboration diagrams are used to show interaction
among different objects
– Package diagrams and deployment diagrams can be used to show
the high level architecture
How do they all fit together?

• Functionality
– use case diagrams

• Decomposition
– class diagrams (class structure)
– package diagrams, deployment diagrams (architecture)

• Behavior
– state diagrams, activity diagrams

• Communication
– sequence diagrams, collaboration diagrams