0% found this document useful (0 votes)
2 views204 pages

UML Basics: Paolo Ciancarini

The document provides an overview of UML (Unified Modeling Language), detailing its evolution from UML 1.* to UML 2.*, and its role as a modeling language for software systems. It discusses the structure and behavior of systems through various canonical diagrams, including use case and class diagrams, and emphasizes the importance of abstraction and relationships in object-oriented modeling. Additionally, it outlines the key components and specifications of UML, including the Object Management Group's role in its standardization.

Uploaded by

np05cp4a220118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views204 pages

UML Basics: Paolo Ciancarini

The document provides an overview of UML (Unified Modeling Language), detailing its evolution from UML 1.* to UML 2.*, and its role as a modeling language for software systems. It discusses the structure and behavior of systems through various canonical diagrams, including use case and class diagrams, and emphasizes the importance of abstraction and relationships in object-oriented modeling. Additionally, it outlines the key components and specifications of UML, including the Object Management Group's role in its standardization.

Uploaded by

np05cp4a220118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UML basics

Paolo Ciancarini
The soul
never thinks
without an image
Aristotle, De Anima
Agenda

• Evolution of UML: UML 1.* and UML 2.*


• Structures, behaviors, interactions
• The basic diagrams of UML 1.*
UML is a modeling language

• A modeling language allows the specification,


the visualization, and the documentation of the
development of a software system
• The models are artifacts which clients and
developers use to communicate
• UML 1.* is a modeling language
• UML 2.* is also a programming language
Meaning of models for software
• A model is a description of the structure
and meaning of a system
• A model is always an abstraction at some
level: it captures the essential aspects of a
system and ignores some details

• Important: a model can be also generator


of potential configurations of systems
Roots of UML

At the beginning of the ’90 there was a convergence:

§ Booch method (Grady Booch) ’94 – join Rational Software


Corporation
§ OMT (Jim Rumbaugh)

§ Fusion/OOSE (Ivar Jacobson) ’95 – joins Rational


Evolution of UML
• OO languages appear, since mid 70’s to late 80’s
• Between ’89 and ’94, OO methods increased from 10 to 50
• Unification of ideas began in mid 90’s pre-UML
• 1994 Rumbaugh joins Booch at Rational
– 1995 v0.8 draft Unified Method
• 1995 Jacobson joins Rational (Three Amigos)
– 1996 June: UML v0.9 published

– 1997 Jan: UML 1.0 offered to OMG


– 1997 Jul: UML 1.1 OMG standard
– 1998: UML 1.2
– 1999: UML 1.3 UML 1.x
– 2001: UML 1.4
• 2003 Feb: IBM buys Rational
– 2003: UML 1.5
– 2004: UML 1.4.2 becomes the standard ISO/IEC 19501

– 2005: UML 2.0


– 2007: UML 2.1.2
– 2009: UML 2.2
– 2010: UML 2.3 UML 2.0
– 2011: UML 2.4
– 2013: UML 2.5
OMG
• Object Management Group, founded in 1989
• Consortium of 800 industries (eg. IBM, HP, Apple, etc.)
and interested universities (Bologna is member)
• Produces specifications of reference architectures, eg.
CORBA
• Other specifications: UML, various MDA technologies
• UML as managed by OMG is a standard de facto in
continuous evolution
• UML1.4 is a ISO standard de jure
Main UML specification documents
• Superstructure:
defines the UML elements (diagrams, etc.)
• Infrastructure: defines the UML core metamodel
• OCL (Object Constraint Language):
formal language for writing predicates,
constraints, and formulas inside diagrams
• XMI (XML Metadata Interchange):
DTD for UML models
• UML Diagram Interchange: XMI + graphic info
Canonical diagrams (vers 1.5)

• Use case
• Class (Object diagrams are class diagrams without classes )
• Behavior
– Statecharts
– Activity
– Interaction
• Sequence
• Collaboration
• Implementation
– Components
– Deployment
Canonical diagrams (Superstructure, vers. 2.4)

Version 2.4 includes 14 canonical diagrams


• Structure
1. Class
2. Composite structure
3. Component
4. Deployment
5. Object
6. Package
7. Profiles (added in version 2.4)
• Behavior
1. Activity
2. Statecharts
3. Usecase
• Interaction
1. Communication
2. Interaction Overview
3. Sequence
4. Timing
UML
2.5
(2013)
Structure and behavior
• UML focusses on two aspects of object
oriented models: structure and behavior
• It aims at visualizing both

Tour Eiffel (1889) G. Balla: Dinamismo di cane al guinzaglio (1912)


Describing the structure of software
• The description of structure offers an
account of what a system is made of, in
terms of both its parts and the
relationships among them
• A structure may be a hierarchy featuring
one-to-many relationships, a network
featuring many-to-many links, or a lattice
featuring connections between
components that are neighbors in space
Network

Hierarchy

Lattice
Organizational
structures
Modules vs components
Discuss
• Which ways do you know to pictorially
describe “behaviors” - or actions?
Flowchart
Assembly
instructions
Napoleon in Russia

(Minard 1869)
Exercise:
structural or behavioral?

Hint: this picture describes modules (static) or components (dynamic)?


Discuss
• Are structures and behaviors all we
need for software design?
Three modeling axes
Functional
Use case diagram
(System sequence diagram)
(Activity diagram)

Static Dynamic
Class diagram State diagram
(Object diagram) Collaboration diagram
Component diagram (Sequence diagram)
(Deployment diagram) (Activity diagram)
Example
• A chess program could be “stand-alone”,
“client-server”, “agent based”, etc.
• Its behavior should always be coherent
with the rules of chess
• What is its goal? To play and win a chess
game against an opponent
Goals and responsibilities
• The very same chess program, with identical structure
and behavior, could be used with a different goal?
• For instance, could it be used to learn to play chess?
Responsibility of the program: teach chess
• Or to write a chess book, like a chess game editor?
Responsibility of the program: write chess texts
• Or to play a game of loser’s chess (where who is
checkmated wins)? Responsibility: play games with rules
slightly different from chess

Each responsibility corresponds to (at least) a use case


From responsibilities to use cases

<<extend>>
Play Play with other rules

Teach

User
Write
Use Case diagram

– It describes the externally observable behavior


of a system, as related to requirements
– It describes the main interactions between the
system and external entities, including users and
other systems
– It is a summary of the main scenarios where the
system will be used
– It describes the main user roles
Example

Negotiate policy

Sales staistics

Customer Insurance Salesperson


Customer statistics
Use Case: elements
association system
boundary

use case

actor Register

Student
Check
Grades
<<include>>

Validate User
Elements of a Use Case Diagram
• Actor:
– Represents a role played by external entities
(humans, systems) that interact with the system
• Use case:
– Describes what the system does (i.e., functionality)
– Scenario: sequence of interactions between the
actors and the system
• Relationships:
– Association between actors and use cases
– Extension (or generalization) among actors
– Dependency among use cases: include and extend
Example

Register
User User

<<include>>
Check Grades
Validate User
Student
Student Faculty Get Roster
<<include>>

<<extend>>
Faculty
Enter Grades
Use Case Scenario
Use Case: Check Grades
Description: View the grades of a specific year and semester
Actors: Student
Precondition: The student is already registered
Main scenario:
User System
1. The system carries out “Validate User”, e.g.,
for user “miner” with password “allAs”.
2. The system prompts for the year and semester.
3. The user enters the year and
semester, e.g., Fall 2013.
4. The system displays the grades of the courses
taken in the given semester, i.e., Fall 2013.
Alternative:
The student enters “All” for the year and semester, and the system displays
grades of all courses taken so far.
Exceptional:
The “Validate User” use case fails; the system repeats the validation use case.
<<extend>> vs
<<include>>
• A use case B is included in
use cases C and D when
these have some common
steps represented by B
• A use case B extends a
use case C when B applies
optionally, under some
condition (usually specified
in the scenario)

• Note: the lower diagram is


formally correct but should be
avoided, because the main
functions should NOT be
described as extensions of
logon
Exercise
Draw a use case diagram and a related scenario
for the following situation:

• A user can borrow a book from a library;


– extend it with borrowing a journal
• a user can give back a book to the library
– including the use case when the user is identified
Exercise: include or extend?
Main use cases: a customer buys something (eg. a book)
from a virtual store like Amazon

• The user must be identified


• The book is not currently available, delayed delivery
• When the book is received the service must be graded
• The book is delivered via air mail
• The book is an ebook and can be delivered via Internet
Structure
diagrams
Object-Oriented Modeling
• Models describe structures of objects and their behavior
• A system is modeled as a set of objects that interact by
exchanging messages
• No semantic gap, seamless development process

Conceptual/computational world
Real world
Abstraction

Interpretation
Data-oriented Object-oriented
Key Ideas of OO Modeling
• Abstraction
– hide minor details so to focus on major details
• Encapsulation
– Modularity: principle of separation of functional concerns
– Information-hiding: principle of separation of design decisions
• Relationships
– Association: relationship between objects or classes
– Inheritance: relationship between classes, useful to represent
generalizations or specializations of objects
• Object-oriented language model
= object (class) + inheritance + message send
The basic building blocks of UML
Water

Fresh water
have
Rivers
Oceans
have

have have
live in Salt water

Fish have
Crocodiles
Penguins

– Elements: domain modeling concepts


– Relationships: connection between model elements
that adds semantic information to a model
– Diagrams: collections of elements and relationships
representing some perspective on a model
Main idea
• With UML we model systems made of
objects which have relationships among
them
• Objects are instances of classes
• Classes define the structure of objects and
their relationships
Example
• A university is an organization where some
persons work, some other study
• There are several types of roles and
grouping entities
• We say nothing about behaviors, for the
moment
A taxonomy
Citizen Female

Foreigner Person Male

Professor Full professor


Student Employee
Administrative Associate
professor
Technician
Research
Undergraduate Masters PhD fellow
student student student
Class
• Is the description of a set of objects
• Defines the structure of the states and the
behaviors shared by all the objects of the
class (called instances)
• Defines a template for creating instances
– Names and types of all fields
– Names, signatures, and implementations of all
methods
Class diagram
• Most common diagram in OO modeling
• A class diagram is a graph including:
– Nodes representing classes (types of objects)
• Nodes can have just a name, or expose some internal structure
– Links representing relationships among classes
• Inheritance
• Association
• Aggregation or composition
• Dependency
– Links can have multiplicities and/or names for roles
played by participants
Class diagram: example
Order Customer class name
dateReceived: Date[0..1] * association 1
isPrepaid: Boolean[1] name[1]
number: String[1]
address[0..1]
attributes
price: Money

class 1
getCreditRating(): String operation
{if
[Link] generalization
is “poor” then [Link]
must be true}
lineItems * {ordered}
constraint
Order line
quantity: Integer Corporate Customer
price: Money contactName
creditRating Personal Customer
* creditLimit

multiplicity creditCardNumber
*
{getCreditRating()==“poor”}
role name salesRep 0..1
1

Product Employee
Notation for classes
• The notation for classes is a rectangular box with
three compartments

ClassName The top compartment shows the class name


field1
……
The middle compartment contains the
declarations of the fields, or attributes, of the
fieldn
class
method1
… The bottom compartment contains the
declarations of the methods of the class
methodn
Example
A point defined by classes at three different abstraction levels

Point

x
Point
y
Move

Point
- x: int
- y: int
+ move(dx: int, dy: int): void
Example
A document defined by classes at three different abstraction levels

Document

Document Pages[]
nPages
display

Document
- Pages: array of Page
- nPages: int
+ display(k:int, p:Page): void
Exercise
Draw a class diagram for the following Java code

class Person {!
private String name;!
private Date birthday;!
public String getName() {!
// …!
}!
public Date getBirthday() {!
// …!
} !
}!
A counter class
Counter class Counter{!
private counter: integer;!
- counter: integer public integer display()!
{return counter};!
public void tic()!
+ display: integer {counter = counter + 1};!
+ tic: void public void reset()!
+ reset: void
{counter = 0};!
A class in UML }!
A corresponding class
in a programming language

c3:Counter p:Printer

Using an object of type class


in an object oriented system
Object diagram
• An object diagram represents a “snapshot” of a
system composed by set of objects
• An object diagram looks like a class diagram
• However, there is a difference: values are
allocated to attributes and method parameters
• While a class diagram represents an abstraction
on source code, an object diagram is an
abstraction of running code
Notation for Objects
• Object: Rectangular box with one or two compartments
• Object name: object name/role name:class name

objectName: Classname The top compartment shows the


name of the object and its class.
field1 = value1
…… The bottom compartment contains
fieldn = valuen a list of the fields and their values.

p1:Point :Point P2/origin:Point

x = 10 x = 30 x = 20
y = 20 y = 30 y = 30

named anonymous named


with role
Object diagrams: examples

p1: Point
homepage: X=0 Y=0
Document

t1: Triangle p2: Point

t =[p1,p2,p3] X=0 Y=1

mythesis:
Document p3: Point

X=1 Y=0
Example (object diagram)
r:Robot
[moving]

w:World

a1:Area a2:Area

w1: Wall w2: Wall d1: Door w3: Wall

width = 36 width = 96 width = 36 width = 96


Example: chemical elements
(class diagram)

Element

C <<covalent>>
Carbon Hydrogen
C H
C
<<covalent>>

59
Example: molecule
(object diagram)

:Hydrogen :Hydrogen

:Hydrogen :Carbon :Carbon :Hydrogen

:Hydrogen :Hydrogen

60
Objects vs. Classes
Interpretation in the Representation in the
real world model
Object An object is anything in the An object has an identity, a
real world that can be state, and a behavior
distinctly identified

Class A class is a set of objects A class defines the structure


with similar structure and of states and behaviors that
behavior. These objects are are shared by all of its
called instances of the class instances
Object = Identity + State + Behavior
• Identity
– Distinguishes an object from all other objects
• State
– Consists of a set of attributes (or fields), which have
names, types, and values
• Behavior
– Defined by the set of operations (or methods) that may
operate on the object
– Each method has a name, a type, and a value, where
• The type consists of the return type and the list of parameter types of
the method, often called signature.
• The value is the implementation of the method often expressed as a
sequence of statements, in languages like Java and C++
Association
• An association is a binary relationship between
classes or objects

• Represented as a line between boxes


Student Course

:John :SwArch
Association and roles
• The simplest relationship among classes is the
association
• An association represents a structural relationship that
connects two classes
• It means that the two classes “know” each other: all
objects in a class have some relationship with some
object(s) in the other class
• An association can have a name, which usually
describes its role
Class diagrams denote systems of objects

from

Flight City
to

from to
Roma:City AZ611:Flight Boston:City
Association with direction
• An association may have an optional label
consisting of a name and a direction arrow
• The direction arrow indicates the direction of
association with respect to the name

enroll
Student Course

An arrow may be attached to the end of path


to indicate that navigation is supported in that direction:

Student knows Course, Course does not know Student


Roles and multiplicity
• An association line may have a role name and a
multiplicity specification
• The multiplicity specifies an integer interval, e.g.,
– l..u closed (inclusive) range of integers
– i singleton range
– 0..* nonnegative integer, i.e., 0, 1, 2, …

0..* 1
Student Faculty
advisee advisor
Association example
• A Student can take up to five Courses
• Every Student has to be enrolled in at least one course
• Up to 300 students can enroll in a course
• A class should have at least 10 students

takes
Student Course
10..300 1..5
Association Example
- Multiplicity
• A teacher teaches 1 to 3 courses
• Each course is taught by only one teacher
• A student can take between 1 to 5 courses
• A course can have 10 to 300 students

1 teaches 1..3
Teacher Course
1..5

takes
Students
10..300
Exercise
Explain the meaning of this diagram

6..* enroll 0..*


Student Course
advisee 0..* 1..*
teach

1
1
Teacher
advisor
Bank Exercise
accountNumber:Integer
0..1
customer

Person Company
manager 0..*
isMarried : Boolean name: String
managedCompanies
isUnemployed : Boolean numberOfEmployees: Integer
birthDate : Date
employee employer
age : Integer 0..* 0..*
stockPrice() : Real
firstName : String
lastName : String
sex : Sex wife
0..1
income(Date) : Integer
husband 0..1

Job
title : String
startDate: Date
Marriage salary: Integer
place: String
date: Date
Net data structures
• How we can represent a net of objects from the
same class?
• A class with an association to itself with both
ends of the association marked with 0..*

a1:A
A 0..*

b1:A d1:A f1:A


0..*

c1:A e1:A g1:A


Hierarchic data structures
• How we can represent a hierarchy of objects from
the same class?
• A class with an association to itself with one end
of the association marked with 0..* (children) and
the other as 0..1 (parent)

a1:A
A 0..*

b1:A d1:A f1:A


0..1

c1:A e1:A g1:A


Hierarchic file system
• A directory can contain any number of
elements (either a file or a directory)
• Any element is part of exactly one directory

*
Element
1

Directory File
Non-hierarchic file system
• A directory can contain any number of
elements (either a file or a directory)
• An element can be part of many directories

*
Element

Directory File
Aggregation
• An aggregation is a special form of association
representing has-a or part-whole relationship
• It distinguishes the whole (aggregate class) from its parts
(component class)
• WARNING: an aggregation does not bind the parts’ lifetime
to the whole (they can exist separately)

Whole Part

Course Students
Example of an aggregation hierarchy

Computer Science
Degree

Calculus Programming Algorithms Geometry OpSystems Logic


Composition
• A composition is a stronger form of aggregation
• It implies exclusive ownership of the component
class by the aggregate class
• The lifetime of the parts is entirely included in the
lifetime of the whole (a part can not exist without
its whole)

Whole Part

Apartment Room
Example of a composition hierarchy

MicrowaveOven

Clock DoorSensor Beeper Display Keypad Lamp


Example

University

1..*
1 1..* 1 0..*
College Department Student

1 1
chair-of member-of

1 1..*
Faculty
Example
sub-team
0..*
0..* 1..*
0..1 Team Employee
1
builds
1..*
1 1..* 0..*
Airplan Component sub-assembly

0..*
assembly
Aggregation vs composition
homePhone
Person PhoneNumber Aggregation:
A Person uses two phone numbers;
workPhone CountryCode Numbers are independent from
Prefix
Number
Persons

homePhone
Person PhoneNumber
Composition:
workPhone CountryCode A Person has two phone numbers;
Prefix Numbers are dependent from
Number Persons
Aggregation vs composition
Windsurf use
0..1 1
Aggregation:
Sail Windsurfs and boats use sails.
The same sail can be used
Boat use
in a Windsurf or in a Boat
0..1 1

Windsurf has
Composition:
0..1 1
Sail Here windsurfs and
boats have each their
Boat has own sails which are
0..1 1
destroyed when the
“container” is
destroyed
Exercise
aggregation or composition ?
– Building and rooms
– Course and lessons
– TV channel and programs
– Parliament and members
– Sky and stars
– Country and cities
– City and buildings
– Wood and trees
Example
Exercise
Imagine some aggregation or composition
relationships among the following classes
and draw a corresponding class diagram
– Employee
– Manager
– Office
– Department
Dependency
• A dependency of A from B is a relationship
between two entities A and B such that the proper
operation of A depends on the presence of B, and
changes in latter would affect the former
• Example: a common form of dependency is the
use relation among classes

<<use>>
Class1 Class2

<<use>>
Program Compiler
Example: dependencies in a class diagram

Registrar CourseSchedule

+ addCourse(s: CourseSchedule, c: Course): void


+ removeCourse(s: CourseSchedule, c: Course): void
Course
+ findCourse(title: String): Course
+ enroll(c: Course, s: Student): void
+ drop(c: Course, s: Student): void

Student

Dependencies are often omitted from a class diagram unless they


convey some significant information
Example: realizing a use case
<<Realizes>>

Collaboration
Use case <<Implements>>
<<Implements>>
<<Implements>>

Class A
Class B
Use case description:
1. Actor pushes button Class C
2. Use case does something
3. Use case responds with Op1()
message Op2() Op1()
4. ... Op2() Op1()
Op2()
Class and superclass
Point

x
y

Point Move

Colored Point Colored Point


color

SetColor
Example

1 1..* call
Phonebill Phonecall 0..* 1 Phone

Origin {complete,disjoint}

Mobileorigin

call from
Mobilecall Cellphone Fixedphone
0..* 0..*
Inheritance
• Key relationship in object modeling
• Inheritance defines a relationship “IS_A” among
classes or interfaces
• In UML there are three kinds of inheritance
– extension relation between two classes (subclass and
superclass)
– extension relation between two interfaces
(subinterface and superinterface)
– implementation relation between a class and an
interface
Three kinds of inheritance
• An extension relation is called specialization and
generalization
• An implementation relation is called realization

Superclass Superinterface Interface

Subclass Subinterface Class

extension of extension of implementation


classes interfaces of interfaces
Interface
<<interface>>
• Interfaces are like classes, List
but have no “implementation”
• A class implementing an add(object o)
interface has a special get(int index)

inheritance arrow toward the


interface
• LinkedList implements List LinkedList

add(object o)
get(int index)
Interfaces in Java

<<interface>>
interface Drawable {
Drawable
void draw(Graphics g);
+ draw(g: Graphics): void
}
Interfaces
• A class and an interface
<<interface>>
differ: a class can have Person
an actual instance of its firstName: String
type (but it can also lastName: String

have zero instances),


whereas an interface
must have at least one
class to implement it Professor Student
• Example: both the salary: Euros major: String
Professor and Student
classes implement the
Person interface
Example

Student
{abstract}

Graduate
No-degree Undergraduate
{abstract}

Master PhD
Example

Student
{abstract}

Graduate
No-degree Undergraduate
{abstract}

Master

PhD
Exercise

• Draw a class diagram showing inheritance


relationships among classes Person,
Employee, and Manager
• Draw a class diagram showing inheritance
relationships among classes Person,
Student, Professor, and Assistant
Real example: online shopping cart

[Link]
Real
example:
LinkedIn
Real example: Facebook
Real example: DOM
Strange examples

A 1 1
A

1 1

A A
Behavior
diagrams

G. Balla: Dinamismo di cane al guinzaglio (1912)


[Link]: Nude descending a staircase (1912)
Modeling Behavior
• Statechart diagram
– Depicts the flow of control inside an object using

DYNAMICS
OBJETC’S
states and transitions (finite state machines)
• Activity diagram
– Describes the control flow among objects by
actions organized in workflows (Petri Nets)
• Sequence diagram

INTERACTION
– Depicts objects’ interaction by highlighting the

OBJETCS’
time ordering of method invocations
• Communication (collaboration) diagram
– Depicts the message flows among objects
Behavioral elements
q Verbs in the requirements
q Dynamic parts of UML models: “behavior over time”
q Usually connected to structural elements

Two primary kinds of behavioral elements:

q Interaction
a set of objects exchanging messages, to accomplish a specific purpose.

harry: Student
ask-for-an-A paul: Professor
name = “Harry White” name = “Paul Smith”

q State Machine
specifies the sequence of states an object goes through during its lifetime in
response to events

received-an-A/buy-beer
inStudy inParty
sober/turn-on-PC
State diagram: booking object
State diagram
• A state diagram represents the behavior of an object
• Graph: net of states (nodes) and transitions (arrows)
• Graph representing a finite state machine
• Useful for modeling a reactive (event-driven) system
• Animation by “token game”
push switch

Off On

push switch
State diagram: elements

Initial State Final State

Transition

Idle Running

State
Example: Unix process

end
fork Pre-empted
Running

Ready scheduled
Sys call

Sys return
Waiting
State
• Situation in the life of an object (or system)
during which it:
– Satisfies some condition,
– Performs some activity, or
– Waits for some events
• Set of values of properties that affect the
behavior of the object (or system)
– Determines the response to an event,
– Thus, different states may produce different
responses to the same event
State in a state diagram
• States are rounded rectangles with at least one section
– Mandatory field: name
• optional: list of internal actions (with optional guards)
– format: event-name argument-list | [ guard condition ] / action-expression
– special actions: 'entry/' and 'exit/' (these cannot have arguments or guards)
• optional: invoking a nested state machine
– format: do/machine-name
– 'machine-name’ must have initial and final states

Enter Password

entry/ set echo


char/ handle char
Counter
class Counter{!
private counter: integer;!
public integer display()!
create {return counter};!
public void tic()!
entry/ set c = 0 {counter = counter + 1};!
public void reset()!
{counter = 0};!
}
tic reset
display

tic display reset


display
tic
entry/ c:=c+1 entry/ print c entry/ c:=0
display

tic display reset

reset

tic
Transition
• Relationship between two states indicating that a
system (or object) in the first state will:
– Perform certain actions and
– Enter the second state when a specified event occurs
or a specified condition is satisfied
• A transition consists of:
– Source and target states
– Optional event, guard condition, and action

Event [Condition] / Action


Source Target
Definition: event and action
• Event
– An occurrence of a stimulus that can trigger a state
transition
– Instantaneous and no duration
• Action
– An executable atomic computation that results in a
change in state of the model or the return of a value
Example

dial digit(n)
[incomplete]

connected Ringing

Dialing Connecting
dial digit(n)
[valid] / connect
dial digit(n)
[invalid] busy
Busy

Invalid
Example

recovery success

recovery failure

anomaly Recovery
Normal
Identification
temperature
pressure
recovery
failure
recovery
Pressure Temperature
success Recovery Recovery
recovery
failure
recovery success
Composite states

Recovery
anomaly

Normal Recovery
Identification
recovery
success
pressure temperature

Pressure Temperature
recovery Recovery Recovery
failure
Composites and transitions

Transition to/from composite state

Active

Idle
Validating

Selecting Processing
Maintenance

Printing

Transition from substate


Including composite states

Dial Number

Include / Dialing

Dialing

[[Link]()]

Start digit(n) Partial Dialing

entry / start dial tone entry / [Link](n)


exit / end dial tone

digit(n)
Composite state
• Used to simplify diagrams
• Inside, it looks like a statechart
• It may have composite transitions
• It may have transitions from substates
• It can be sequential or parallel
Example

[not all assets added]


Adding assets

do / add assets

[all assets added]

Verify assets [verified /complete check out]


Check out assets
do / verify eligibility
cancel
cancel

cancel
Cancelled Complete
Exploiting
a
composite
state
Parallel composition
• Concurrency (multiple threads of control)
• Synchronization

Superstate

substate1 substate2

substate3 substate4
Example

Incomplete

Mod1 Mod2

Project Passed

fail
Midterm Final Failed
Protocol state machine
• Normally we use a state diagram to show the internal
behavior of all objects of a class
• Sometimes, however, we want to show a complex
protocol (set of rules governing communication) when
using an interface for a class
• For example, when we access a database we need to
use operations like open, close and query. But these
operations must be called in the right order: we cannot
query the database before we open it
Protocol state
machine
<<boundary>>
DatabaseAccessor

-dbname
-password
-comArea
-queryStatement
DBaccess
+open()
+close()
+query()
+fetch()
+cancel()
+create()
+kill()
Behavioral vs protocol state machine

• Two kinds of state machines: behavioral state


machines and protocol state machines
• Behavioral state machines can be used to model
the behavior of individual entities (e.g., class
instances)
• Protocol state machines are used to express
usage protocols and can be used to specify the
legal usage scenarios of classifiers, interfaces,
and ports
History pseudo state
• A history pseudostate represents the most recent active substate of
its containing state
• There are two kinds of this pseudostate: shallow or deep
– Shallow (H): only the topmost active level of superstate is recorded
– Deep (H*): all nested active levels in the superstate are recorded
(See the Superstructure sect 15.3.8 for pseudostate definitions and icons)
Consistency
among diagrams attends
Student
practices
* Name *
Surname
Age
Role 0..*
1
UniversityCourse Sport

new enrollment to
a different course

Student

change role
end studying
studies

change career
Graduate Sportsman
Exercise: Cellular Phone

• Draw a statechart describing the operation of a


cellular phone. Assume that the phone has keys for:
– power on and off
– keypad locking and unlocking
– 0-9, #, and *
– talk (or send) and end
Model the following operations:
– power on/off
– keypad locking/unlocking
– making calls (e.g., dialing, connecting, talking),
– receiving calls (e.g., ringing, talking)
Activity diagrams
• Activity diagrams represent workflows of actions
of several objects (but objects are not shown)
• Actions are composed by sequence, choice,
iteration, and concurrency
• AD can be used to describe the activities of the
components of a system
• In UML1 AD are based on State Diagrams
in UML2 they have a different semantics
Activity diagram: elements

initial

Initialize course Activity (rounded rectangle)

Add student
A diagram whose nodes
fork/spawn
represent activities,
while arrows represent the
Notify Registrar Notify Billing order the activities happen

synchronization

decision [else]

[ count < 10 ]
guard
Close course final
Example
[incorrect]
Fill out Obtain help
enrollment forms to fill out forms
[correct]
Enroll in
university
Attend university
[accepted] overview presentation

[rejected]
Enroll in seminars Make initial
tuition payment
Example
Receive order

Fill order Send invoice

[rush order] [else]

Overnight delivery Regular delivery Receive payment

Close order
Activity diagram
Example: hotel reservation
Activity control nodes
• Initial node • Merge node
• Decision node • Activity final node
• Fork node • Flow final node
• Join node
Activity partition
• Partitions divide the diagram to constrain and show some special view
• Partitions often correspond to organizational units in a business model
Swimlanes
in an
activity diagram
showing a
workflow
with several roles
Exercise Which is the maximum degree of
parallelism in this activity diagram?
What an AD does not show?
• Objects (but they can be inferred)
• States
• Messages
• Data passed between steps
• User interface
How to create an AD
1. Identify the activities (steps) of a process
2. Identify who/what performs activities (process steps)
3. Identify decision points (if-then)
4. Determine if a step is in loop
5. Determine if a step is parallel with some other
6. Identify the order of activities, decision points
Example
Step Process Step Who/What Parallel Loop Preceding
ID or Decision Performs Activity Step

1 Request quote Customer No No -

2 Develop Salesperson No Yes 1


requirement
notes
3 Decision: Help? Salesperson - Yes 2

4 Salesperson Salesperson No Yes 3


enters data
5 Check Technical No Yes 3
requirements Expert
6 Tech. expert Technical No Yes 5
enters data Expert

7 Calculate quote System No Yes 4, 6

8 Review quote Customer No Yes 7

9 Decision: Customer No Yes 8


Changes?
10 Accept quote as Customer No No 9
order
How to create an AD (cont.)
7. Draw the swimlanes
8. Draw the start point of the process in the swimline of the first
activity (step)
9. Draw the oval of the first activity (step)
10. Draw an arrow to the location of the second step
11. Draw subsequent steps, while inserting decision points and
synchronization/loop bars where appropriate
12. Draw the end point after the last step.
1

5
3

4 6

Example
8

10
State vs activity diagrams
• Both diagrams describe behaviors, by state
changes and actions, respectively
• In UML1 they are equivalent (in AD states are
actions)
• In UML2 they differ: ActivityD are based on Petri
Nets, StateD on Harel automata
• Their typical usage is also different:
– State diagrams are single context
– Activity diagrams are multiple context
State machine: chess game

Black wins

White’s move
start stalemate
black white
Draw
moves moves
stalemate

Black’s move
White wins
Activity diagram: chess game
White

move move

move move
Black
State vs activity diagrams

e2e4 e7e5 g1f3 b8c6


White

Pe2e4 Ng1f3

Pe7e5 Nb8c6
Black
State vs activity diagrams
Activity diagram vs flowchart
• An activity diagram shows the order in
which to do tasks
• The key difference between an activity
diagram and a flowchart is that the activity
diagram can describe parallel processes,
while flowcharts are sequential
Behavior
diagrams:
interaction
Balla: Dinamismo di cane al guinzaglio, 1912
Modeling Interaction
• Statechart diagram
– Depicts the flow of control inside an object using
states and transitions (finite state machines)
• Activity diagram
– Describes the control flow among objects by
actions organized in workflows (Petri Nets)
• Sequence diagram

INTERACTION
– Depicts objects’ interaction by highlighting the
time ordering of method invocations
• Communication (collaboration) diagram
– Depicts the message flows among objects
Interaction diagrams
• A use case diagram presents an outside view of
the system
• The inside view of a system is shown by
interaction diagrams

• Interaction diagrams describe how a use case is


realized in terms of interacting objects
• Two types of interaction diagrams
– Sequence diagrams
– Collaboration (Communication) diagrams
Sequence diagram: main entities
• participant: an object that acts in the
sequence diagram
• message: communication between
participant objects
• the axes in a sequence diagram:
– horizontal: which object/participant is acting
– vertical: time (down -> forward in time)
Sequence diagram: elements

object

lifetime
activation message
bar
Sequence diagram
Messages between objects
• message (method call) indicated by an
horizontal arrow to another object
– write the message name and arguments above arrow

– dashed arrow back indicates return


– different arrowheads for synchronous / asynchronous
methods
Arrows in a sequence diagram
• A sequence diagram describes sequences
of method calls among objects
• There are several types of method calls
Example with different msgs
Lifetime of objects
• creation: arrow with 'new'
label
– an object created after
the start of the scenario
appears lower than the
others
• deletion: an X at bottom of
object's lifeline
– Java does not explicitly
delete objects; they fall
out of scope and are
garbage-collected
163
Indicating method calls
• activation: thick box over object's life line
– The object is running its code, or it is waiting for
another object's method to finish
– nest to indicate recursion

Activation
:Controller

Nesting
Sequence diagram: flow

: Customer : Order : Payment : Product : Supplier

place an order

process

validate
Sequence of message transmissions

if ( payment ok )
if ( not in stock )
deliver
back order

get address

mail to address
Linking sequence diagrams
• if a sequence diagram is too large or refers to
another diagram, indicate it with either:
– an unfinished arrow and a comment
– a ref frame that names the other diagram

Customer Info ref

Verify customer credit

Approved?
Conditionals and loops
• frame: box around part of a sequence diagram to
indicate selection or loop
– if : (opt) [condition]!
– if-else: (alt)[condition] else [condition]
– loop: (loop)[condition to loop over]!

Examples: see the next three slides


Opt
(if)
Alt
(if-else)
Loop
Example
A SD highlights the objects involved in an activity
and the time ordering of method calls among them

[Link]
Example
Example
Using a SD for workflow
A real
example
(from
[Link])
Consistency among diagrams
We can derive the dependencies shown in a class diagram
from the interactions defined in a sequence diagram
buys valid for
Transaction Ticket Zone

amount paid Coin


Balance
Bill

:Traveler :TicketDistributor :Zone :Balance


selectZone() getPrice()
amountDue
insertChange()
updateBalance()
amountDue

insertChange()
updateBalance()
ack
<<create>> :Ticket
printedTicket
Exercise
Draw a sequence diagram showing how a
customer interacts with a travel agency, a station
and a train to reach some destination

Draw a sequence diagram to show how a user


prints a document on a printer, and a counter
keeps a count of printed pages
Communication (collaboration) diagram

• Communication diagrams show the


message flow between objects in an
application
• They also show implicitly the basic
associations between classes
• Communication diagrams are drawn in the
same way as sequence diagrams (and
can be semantically equivalent to them)
Communication diagram
object
: Order 1.1 : ok := validate() : Payment

link
1.2 [ok] : deliver(c)

1 : place an order(c)
c : Customer 1.2.2 : get address() p : Product

1.2.1 [not in stock] : back order(p)


message

: Supplier
Communication diagram
Collaboration 1.1 : ok := validate() : Payment
: Order

1.2 [ok] : deliver(c)

1 : place an order(c)
c : Customer 1.2.2 : get address() p : Product

1.2.1 [not in stock] : back order(p)

: Supplier
Example
SD vs CD

• These two diagrams are


equivalent
• Communication diagrams
correspond to simple
Sequence diagrams that
use none of the
structuring mechanisms
such as interaction uses
or combined fragments
• Some complex sequence
diagrams can not be
represented by equivalent
communication diagrams
Consistency among diagrams
Exercise
Draw a communication diagram showing how a
customer interacts with a travel agency, a station
and a train to reach some destination

Draw a communication diagram to show how a


user prints a document on a printer, and a counter
keeps a count of printed pages
Basic diagrams we have seen
Other diagrams
Diagrams we have seen in this lecture:
• Use case, class, object, statechart, activity,
interaction (sequence and collaboration)
We could add (using UML 1.*):
• Component, Deployment
We could add (using UML 2.*):
• Composite structure, Profiles, Package,
Interaction Overview, Timing
Usage survey

See also: [Link]/Home/resources-for-you-1/the-uml-survey-results-are-in


Main diagrams
The main diagrams that are used in most
views are :
• Use case diagram
• Class diagram
• Sequence diagram
• Activity diagram
Discuss
• Which diagrams are most useful in each
lifecycle phase?
Diagrams in lifecycle

... Requirements ... Design ... Implementation

Use Case

Class diagram

Sequence diagram

Activity diagrams and Statecharts


Diagrams during design
Three main types:
• Class diagrams for domain entities and
data structures
• Sequence diagrams for multiple objects
interactions via messages
• Statecharts for behaviors and algorithms
of a single object
Exercise
Draw, on some game-playing domain (eg. Chess):
– A class diagram
– An object diagram
– A statechart
– A sequence diagram
– A communication diagram
– An activity diagram
Conclusions
• UML is a notation still evolving under control of OMG
• It offers several diagram types, in order to describe
different views on a model
• Basic diagrams from UML 1.* are: use cases, classes,
behaviors (statechart+activity), interactions (sequence
+communication)
• Several tools available
• UML and the diagrams need a process to be used
consistently and effectively (for instance, RUP)
Summary
• UML includes a number of diagram-based
notations to model software systems
using an object oriented approach
• UML is not a process (it needs a process,
like for instance the RUP)
• It is not proprietary: it is an OMG (Object
Management Group) and ISO standard
Caveat emptor
When Jim, Ivar, and I began our journey that became manifest in the UML,
we never intended it to become a programming language…UML was to be
a language for visualizing, specifying, constructing, and documenting the
artifacts of a software-intensive system—in short, a graphical language to
help reason about the design of a system as it unfolds.
Most diagrams should be thrown away, but there are a few that should be
preserved, and in all, one should only use a graphical notation for those
things that cannot easily be reasoned about in code.
As I've also often said, the code is the truth, but it is not the whole truth,
and there are things such as rationale, cross-cutting concerns, and
patterns that cannot easily be recovered or seen from code…
These are the things for which a graphical notation adds value, and any
such notation should be used only if it has predictive power or reasoning
power (meaning, you can ask questions about it).
Grady Booch
Self test questions
• Which are the UML 1.* canonical diagrams?
• What is a use case?
• What is a class diagram? What is an object diagram?
• How do we describe a tree-like data structure in a
class diagram?
• What is an interaction diagram?
• What is a protocol state machine?
• What is the difference between statecharts and
activity diagrams?
Readings
• On use cases
[Link]/developerworks/rational/library/[Link]!

• On class diagrams
[Link]/developerworks/rational/library/content/
RationalEdge/sep04/bell/[Link]!

• On activity diagrams
[Link]/developerworks/rational/library/[Link]!

• On sequence diagrams
[Link]/developerworks/rational/library/[Link]!
!
UML Specification Documents
• OMG, UML Specification version 1.5, 2003
• OMG, UML Superstructure version 2.4.1, 2011
• Rumbaugh, Jacobson, Booch, The UML Reference
Manual, Addison Wesley, 1999 and 2004 (2nd ed)
References on using UML
• Booch, Rumbaugh, Jacobson, The UML User Guide,
Addison Wesley, 1998 and 2005 (2ed)
• Fowler, UML Distilled, 3ed, Addison Wesley, 2003
• Pilone and Pitman, UML 2.0 in a Nutshell, OReilly, 2005
• Ambler, The Elements of UML 2.0 Style, Cambridge
University Press, 2005"
Useful sites
• [Link] Documents defining the standard!
• [Link]!
• [Link]/!
• [Link]/essays/[Link]!
• [Link]/uml/[Link]!
• [Link]/software/awdtools/rmc/library!
• [Link]/en-us/library/[Link]!
• [Link]/courses/cs211/ATMExample!
• [Link]!
• [Link]/uml/!
• [Link]/ITMUML/[Link] Online courseware
• [Link]/modeling/mdt/uml2/docs/articles/Getting_Started_with_UML2/[Link]
Tools
• Eclipse + several plugins, like Omondo
• [Link] Argo or Poseidon
• [Link] free online tool, sharable diagrams
• [Link] web application, need license!
• [Link] Open source editor for UML!
• [Link]/us/products/together/[Link] Borland Together
• [Link] Visual Paradigm suite!
• [Link] Magicdraw suite!
• [Link] text UML!
• [Link] web application for class and seq diagrams!
• [Link]/software/rational/ Rational Rose
• [Link] IBM platform
• [Link] UML on tablet PC!
• [Link] Beautiful UML diagrams in LaTeX
• [Link]/uml Images reusable in a graphic editor!
• [Link] Fast draw of UML diagrams for web pages!
UML blogs and fan clubs
• [Link]/groups/UML-Lovers-143183/about
• [Link]/uml-and-sysml/
• [Link]/about-geert-bellekens/
Questions?

You might also like