Post on 18-Dec-2015
Advanced Modeling with UML
Karin Palmkvist, Bran Selic, Jos Warmer and Nathan Dykman
UML Revision Task Force
Object Modeling with OMG UML Tutorial Series
© 1999-2001 OMG and Contributors: Crossmeta, EDS, IBM, Enea Data, Hewlett-Packard, IntelliCorp, Kabira Technologies, Klasse Objecten, Rational Software, Telelogic, Unisys
Advanced Modeling with UML 2
Overview Introduction Advanced Modeling
Part 1: Model Management Karin Palmkvist, Enea Data
Part 2: Extension Mechanisms and Profiles
Bran Selic, Rational Software Nathan Dykman, Hewlett Packard
Part 3: Object Constraint Language (OCL) Jos Warmer, Klasse Objecten Bran Selic, Rational Software
Advanced Modeling with UML 3
Tutorial Series
Lecture 1: Introduction to UML: Structural and Use Case Modeling
Lecture 2: Behavioral Modeling with UML
Lecture 3: Advanced Modeling with UML
[Note: This version of the tutorial series is based on OMG UML Specification v. 1.4, UML Revision Task Force recommended final draft, OMG doc# ad/01-02-13.]
Advanced Modeling with UML 4
Tutorial Focus: the Language
language = syntax + semantics syntax = language elements (e.g.
words) are assembled into expressions (e.g. phrases, clauses)
semantics = the meanings of the syntactic expressions
UML Notation Guide – defines UML’s graphic syntax
UML Semantics – defines UML’s semantics
Advanced Modeling with UML 5
«metamodel»UML
Foundation
Model Management
Behavioral Elements
dependency
package
UML Overview
Advanced Modeling with UML 6
Foundation
Model Management
Behavioral Elements
CoreExtension Mechanisms
Data Types
UML Overview
Advanced Modeling with UML 7
Behavioral Elements
Model Management
Foundation
Use Cases State Machines Activity GraphsCollaborations
Common Behavior
UML Overview
Advanced Modeling with UML 8
Advanced Modeling with UML
Part 1: Model Management Part 2: Extension Mechanisms and Profiles Part 3: Object Constraint Language (OCL)
Advanced Modeling with UML 9
«metamodel»UML
Foundation
Model Management
Behavioral Elements
UML Overview
Advanced Modeling with UML 10
Model Management Overview
Main UML constructs used for model management: Package Subsystem Model
Advanced Modeling with UML 11
Unifying Concepts
Packages, Subsystems, and Models Group other model elements together Each groups elements for a different
reason (providing different semantics) Other grouping elements in UML
include: Classes Components
Advanced Modeling with UML 12
Package
What are Packages? Core Concepts Diagram Tour When to Use Packages Modeling Tips
Advanced Modeling with UML 13
Package
A package is a grouping of model elements
Advanced Modeling with UML 14
Package – Example
OrderCustomer
Location Item
Stock Item Order Item
Sales
Warehouse
Advanced Modeling with UML 15
Package
A package can contain model elements of different kinds Including other packages to create
hierarchies A package defines a namespace
for its contents Packages can be used for various
purposes
Advanced Modeling with UML 16
Core Concepts
Construct Description Syntax
Access
Import A dependency indicating that the public contents of the target package are added to the namespace of the source package.
«import»
A dependency indicating that the public contents of the target package are available in the namespace of the source package.
«access»
Package A grouping of model elements.Name
Advanced Modeling with UML 17
Visibility
Each contained element has a visibility relative to the containing package A public element is visible to elements
outside the package, denoted by ‘+’ A protected element is visible only to
elements within inheriting packages, denoted by ‘#’
A private element is not visible at all to elements outside the package, denoted by ‘-’
Same syntax for visibility of attributes and operations in classes
Advanced Modeling with UML 18
X Y
Import
«import»A
B +C-D
+E
A
B +C-D
+E
X Y
Y::C
Y::E
«import»
The associations are owned by package X
Advanced Modeling with UML 19
Import – Alias
An imported element can be given a local alias and a local visibility
«import»A
B +B-D
+E
X Y
A
B +B-D
X Y
+E«import»
+Y::E
+Y::B-C
same class
Advanced Modeling with UML 20
A
B +C-D
+E
X Y«access»
X Y
Access
The associations are owned by package X
«access»A
B +C-D
+E
Advanced Modeling with UML 21
X Y Z
Import vs. Access
«import»
A
B +C-D
+E
«import»
+G
+F
-H
-Z::G
+Z::F
«access» «access»
X Y Z
A
B +C-D
+E +G
+F
-H
Y::C
Y::E
Y::F
Advanced Modeling with UML 22
Package Inheritance
A package with a generalization to another package inherits public and protected elements that are owned or imported
by the inherited package
Advanced Modeling with UML 23
Diagram Tour
Packages are shown in static diagrams Two equivalent ways to show containment:
Advanced Modeling with UML 24
When to Use Packages
To create an overview of a large set of model elements
To organize a large model To group related elements To separate namespaces
Advanced Modeling with UML 25
Modeling Tips – Package
Gather model elements with strong cohesion in one package
Keep model elements with low coupling in different packages
Minimize relationships, especially associations, between model elements in different packages
Namespace implication: an element imported into a package does not “know” how it is used in the imported package
Advanced Modeling with UML 26
Subsystem
What are Subsystems? Core Concepts Diagram Tour When to Use Subsystems Modeling Tips
Advanced Modeling with UML 27
Subsystems are used for system decomposition
Subsystem
Advanced Modeling with UML 28
Subsystem – Example
TrunkTraffic Control
Subscription
Communicating subsystems constitute a system
Advanced Modeling with UML 29
Core Concepts
Subsystem
Construct Description Syntax
A grouping of model elements that represents a behavioral unit in a physical system.
Name
Advanced Modeling with UML 30
Subsystem Aspects
A subsystem has two aspects: An external view, showing the
services provided by the subsystem
An internal view, showing the realization of the subsystem
There is a mapping between the two aspects
Advanced Modeling with UML 31
Subsystem Aspects
A subsystem has a specification and a realization to represent the two views
Realization elementsSpecification elements
Advanced Modeling with UML 32
Subsystem Realization
The subsystem realization defines the actual contents of the subsystem
The subsystem realization typically consists of classes and their relationships, or a contained hierarchy of subsystems with classes as leaves
Realization elementsSpecification elements
?
Advanced Modeling with UML 33
The subsystem specification defines the external view of the subsystem
Realization elementsSpecification elements
?
Subsystem Specification
Advanced Modeling with UML 34
Subsystem Specification
The subsystem specification describes the services offered by the
subsystem describes the externally experienced
behavior of the subsystem does not reveal the internal structure
of the subsystem describes the interface of the
subsystem
Advanced Modeling with UML 35
Specification Techniques
The Use Case approach The State Machine approach The Logical Class approach The Operation approach
…and combinations of these.
Advanced Modeling with UML 36
For subsystem services used in certain sequences When the specification is to be understood by non-
technical people
Realization elementsSpecification elements
Use Case Approach
Advanced Modeling with UML 37
Use Case Approach – Example
Traffic Control
Specification elements Realization elements
Change Digit Analysis Information
Initiate Call
Receive Digit and Connect
Hook Signal and Disconnect
Operator
Trunk
Subscription
Advanced Modeling with UML 38
State Machine Approach
For subsystems with state dependent behavior
Specification elements
Stopped Running
Error
Maintenance
Exhausted
Traffic Control
Focuses on the states of the subsystem and the transitions between them
Advanced Modeling with UML 39
Specification elements
AnalyzerNumber
Dictionary
Network Manager
Traffic Control
Logical Class Approach
When usage of the subsystem is perceived as manipulation of objects
When the requirements are guided by a particular standard
Advanced Modeling with UML 40
Operation Approach
For subsystems providing simple, “atomic” services
OperationsinitiateConnection (…)
dialledDigit (…)
throughConnect (…)
bAnswer (…)
bOnHook (…)
aOnHook (…)
Traffic Control
When the operations are invoked independently
Advanced Modeling with UML 41
Mixing Techniques
Traffic Control
changeDigitAnalysisInformation (...)
Initiate Call
Receive Digit and Connect
Hook Signal and DisconnectSubscription
Trunk
Specification elements
Specification elements
Operations
Advanced Modeling with UML 42
The complete subsystem symbol has three pre-defined compartments
Realization elements
Specification elements
Operations
Complete Subsystem Notation
Each of the compartments may be optionally omitted
from the diagram
Advanced Modeling with UML 43
Subsystem Interfaces
TrunkTraffic Control Subscription
TrunkTraffic Control Subscription
Advanced Modeling with UML 44
Operations
operation1( ) : Type1
operation2( ) : Type2
operation3( ) : Type3
operation4( ) : Type4
operation5( ) : Type5
«Interface»
«realize»operation1( )operation2( )operation4( )
«Interface»
«realize»operation2( )operation3( )operation5( )
Operations and Interfaces
The subsystem must support all operations in the
offered interfaces
Advanced Modeling with UML 45
Specification elements«Interface»
«realize»
«Interface»
«realize»
Subsystem Interfaces
An interface operation may alternatively be supported by a specification element of the subsystem
Advanced Modeling with UML 46
Specification – Realization
The specification and the realization must be consistent
The mapping between the specification and the realization can be expressed by: realization relationships collaborations
Advanced Modeling with UML 47
Operations
operation1( ) : Type1
operation2( ) : Type2
operation3( ) : Type3
operation4( ) : Type4
operation5( ) : Type5
Realization Elements
«realize»
operation1( )
Realize Relationship
Realization is particularly useful in simple mappings
Advanced Modeling with UML 48
Realize – Example
Realization elements
Specification elements
changeDigitAnalysisInformation ( )
Initiate Call
Receive Digit and Connect
Hook Signal and DisconnectSubscription
Traffic Control
Operations
Trunk
changeDigitAnalysisInformation ( )::
«realize»
Advanced Modeling with UML 49
Collaboration
A collaboration defines the roles to be played when a task is performed
The roles are played by interacting instances
Sequence Diagram
:Trunk :Traffic Control :Subscription
markBusy
dialledDigit
dialledDigit
throughConnect
bAnswer
markBusy
Collaboration Diagram
:Trunk
:Traffic Control
:Subscription
3: dialledDigit6: bAnswer
5: markBusy1: markBusy
4: throughConnect
2: dialledDigit
Advanced Modeling with UML 50
Collaboration – Notation
A collaboration and its participants
Collaboration
Role
Class
role name
role namerole name
role name
Advanced Modeling with UML 51
Specification elements Realization elements
Receive Digit and Connect
Hook Signal and Disconnect
Initiate Call
CoordinatorAnalysisDatabase
NetworkInterface
Collaboration – Example
Collaborations are useful in more complex situations
Advanced Modeling with UML 52
Subsystem Interaction
1:transmit
4:receive
2:send
3:ack
1.4
Advanced Modeling with UML 53
Communicating with Subsystems
Two approaches: Open subsystem - public elements
are accessed directly Closed subsystem - access via the
subsystem itself
1.4
Advanced Modeling with UML 54
Open Subsystems
A subsystem is called open if its realization is used directly by the environment
Traffic Control
Trunk
-B
+A
«import»
+TC::A
+B
-C
The specification acts as an overview of
the subsystem as a requirements
specification
1.4
Advanced Modeling with UML 55
Closed Subsystems
A subsystem is called closed if its realization is not directly used by the environment
Traffic Control
Trunk
+A
-B
+B
-C
The specification acts as an overview of the
subsystem as a requirements
specification as a specification of
how to use the subsystem
1.4
Advanced Modeling with UML 56
Subsystem Instance
A subsystem instance is the runtime representation of a subsystem. Its task is to handle incoming stimuli.
1.4
:Traffic Control
Advanced Modeling with UML 57
Subsystem Inheritance
A subsystem with a generalization to another subsystem inherits public and protected elements that are owned or imported
by the inherited subsystem Both specification elements and
realization elements are inherited Operations are also inherited
Advanced Modeling with UML 58
Diagram Tour
Subsystems can be shown in static diagrams and interaction diagrams
“Fork” notation alternative for showing contents:
Realization elementsSpecification elements
Realization elements
Advanced Modeling with UML 59
Diagram Tour – continued
Subsystems can be shown in interaction diagrams collaboration diagrams sequence diagrams
Sequence Diagram
Advanced Modeling with UML 60
When to Use Subsystems
To express how a large system is decomposed into smaller parts
Distributed development To express how a set of modules
are composed into a large system For component based development
Advanced Modeling with UML 61
Specification Elements
Realization Elements
ShoppingCart
Component Based Development
ArtStoreClient
ContextObject
«auxiliaryClass»
ShoppingCartDBbroker
«auxiliaryClass»
ShoppingCart
«Interface»
getItemCount(…)setItemCount(…)getTotal(…)setTotal(…)...
ShoppingCartHomecreate(…)
findByPrimaryKey(…)...
«Interface»
RemoteObject
«auxiliaryClass»
HomeObject
«auxiliaryClass»
«call»
«call»ShoppingCartImpl
«focalClass»«call»
ShoppingCartHome
«call»
ShoppingCart
Context
An EJB component modeled using a subsystem and classes stereotyped «focalClass» or «auxiliaryClass»
1.4
Advanced Modeling with UML 62
Modeling Tips – Subsystem
Define a subsystem for each separate part of a large system
Choose specification technique depending on factors like kind of system and kind of subsystem
Realize each subsystem independently, using the specification as a requirements specification
Advanced Modeling with UML 63
Model
What are Models? Core Concepts Diagram Tour When to Use
Models Modeling Tips
Advanced Modeling with UML 64
Model
A model captures a view of a system, with a certain purpose. It is a complete description of those aspects of the system relevant to the purpose of the model, at the appropriate level of detail.
Advanced Modeling with UML 65
Model – Example
Design Model
Use Case Model
Advanced Modeling with UML 66
Core Concepts
Model
Trace
Construct Description Syntax
A dependency connecting model elements that represent the same concept within different models. Traces are usually non-directed.
«trace»
A view of a system, with a certain purpose determining what aspects of the system are described and at what level of detail.
Name
Advanced Modeling with UML 67
Trace
Analysis
Design
«trace»
Advanced Modeling with UML 68
Model Inheritance
A model with a generalization to another model inherits public and protected elements that are owned or imported
by the inherited model
Advanced Modeling with UML 69
Diagram Tour
Models as such are seldom shown in diagrams
Two equivalent ways to show containment:
Advanced Modeling with UML 70
Model vs. Diagram
Use Case Model
Diagrams make up the documentation of a model
Design Model
Advanced Modeling with UML 71
When to Use Models
To give different views of a system to different stakeholders
To focus on a certain aspect of a system at a time
To express the results of different stages in a software development process
Advanced Modeling with UML 72
Modeling Tips – Model
Define the purpose for each model A model must give a complete
picture of the system, within its purpose
Focus on the purpose of the model; omit irrelevant information
Advanced Modeling with UML 73
Models and Subsystems
Models and subsystems can be combined in hierarchies:
Advanced Modeling with UML 74
Wrap Up Model Management
Packages are used to organize a large set of model elements Visibility Import Access
Subsystems are used to represent parts of a system Specification Realization
Models are used to capture different views of a system Trace
Advanced Modeling with UML 75
Advanced Modeling with UML
Part 1: Model Management Part 2: Extension Mechanisms and
Profiles Part 3: Object Constraint Language (OCL)
Advanced Modeling with UML 76
Semantic Variations in UML
UML contains semantic aspects that are: undefined (e.g., scheduling discipline), or ambiguous (multiple choices/interpretations)
Why is this the case? UML can’t address every domain perfectly Different domains require different specializations
But, if UML can be extended in arbitrary ways, what is the value of having a standard?
Advanced Modeling with UML 77
UML as a “Family of Languages”
The standard can be specialized for different domains in effect: refinements of the standard
UML 1.4 StandardUML 1.4 Standard
UML for Real TimeUML for Real Time etc.UML for CORBAUML for CORBA
UsingUsingextensibilityextensibilitymechanismsmechanisms
UsingUsingextensibilityextensibilitymechanismsmechanisms
Advanced Modeling with UML 78
Extensibility Mechanisms
Extensibility Mechanisms Allow Modelers to refine the semantics
of UML for a specific domain Extensions cannot violate the
standard UML semantics Enforces a consistent core of concepts
and semantics for every variation Prevents meta-model explosion (Using
UML to model everything and anything)
Advanced Modeling with UML 79
How UML Extensibility Works
The standard UML semantics can be viewed as defining a space of possible interpretations
Standard UML semanticsStandard UML semanticsStandard UML semanticsStandard UML semantics
refined semanticsrefined semantics(valid)(valid)refined semanticsrefined semantics(valid)(valid) different semanticsdifferent semantics
(NOT valid)(NOT valid)different semanticsdifferent semantics(NOT valid)(NOT valid)
Advanced Modeling with UML 80
Models
A model is a description of something “a pattern for something to be made” (Merriam-
Webster)
blueprint(model)
building building
model thing that is modeled The Map is Not The Territory
Advanced Modeling with UML 81
Meta-Models
Are Simply Models of Models
ClassClassClassClass AssociationAssociationAssociationAssociation
ObjectsObjects
ModelModel
Meta-ModelMeta-Model
(M0)(M0)
(M1)(M1)
(M2)(M2)
<sawdust><sawdust><2 tons><2 tons><sawdust><sawdust><2 tons><2 tons>
<Ben&Jerry’s><Ben&Jerry’s><Ben&Jerry’s><Ben&Jerry’s> <lard><lard><5 tons><5 tons><lard><lard><5 tons><5 tons>
CustomerOrderCustomerOrderCustomerOrderCustomerOrder
itemitemquantityquantityitemitemquantityquantity
CustomerCustomerCustomerCustomer
idididid
Advanced Modeling with UML 82
The UML Meta-Model
Is a UML Model of UML
GeneralizableElementGeneralizableElementGeneralizableElementGeneralizableElement
isRoot : BooleanisRoot : BooleanisLeaf : BooleanisLeaf : BooleanisAbstract : BooleanisAbstract : Boolean
isRoot : BooleanisRoot : BooleanisLeaf : BooleanisLeaf : BooleanisAbstract : BooleanisAbstract : Boolean
ClassClassClassClass
isActive : BooleanisActive : BooleanisActive : BooleanisActive : Boolean
ClassifierClassifierClassifierClassifier
FeatureFeatureFeatureFeature
visibility : {public, private,visibility : {public, private,protected}protected}visibility : {public, private,visibility : {public, private,protected}protected}
**
not self.isAbstract implies self.allOperations->forAll(op | self.allMethods->exists(m | m.specification includes (op)))
not self.isAbstract implies self.allOperations->forAll(op | self.allMethods->exists(m | m.specification includes (op)))
Well-formedness constraint (OCL)Well-formedness constraint (OCL)
Meta-ClassMeta-ClassMeta-ClassMeta-Class
Advanced Modeling with UML 83
The UML Meta-Model
Put another way, UML uses (a part of) itself as a Meta-language Other examples: Scheme, Lisp,
Smalltalk This small subset of UML is used to
describe all of UML The subset contains classes,
associations, operations, constraints, generalization, etc.
This core subset is related to MOF (more on MOF in Part 4)
Advanced Modeling with UML 84
The Basic Extensibility Mechanisms
Stereotypes used to refine meta-classes (or other
stereotypes) by defining supplemental semantics
Constraints predicates (e.g., OCL expressions) that reduce
semantic variation can be attached to any meta-class or stereotype
Tagged Values individual modifiers with user-defined semantics can be attached to any meta-class or stereotype
Advanced Modeling with UML 85
Stereotypes Used to define specialized model elements
based on a core UML model element Defined by:
Base metaclasses (or stereotype) What element is specialized?
Constraints: What is special about this stereotype?
required tags (0..*) What values does this stereotype need to know?
icon How should I appear in a model?
A model element can be stereotyped in multiple different ways
1.4
Advanced Modeling with UML 86
Example
Capsule: A special type of concurrent object used in modeling certain real-time systems
By definition, all classes of this type: are active (concurrent) have only features (attributes and operations)
with protected visibility have a special “language” characteristic used
for code generation purposes
In essence, a constrained form of the general UML Class concept
Advanced Modeling with UML 87
Example: Stereotype Definition
Using a tabular form:
Stereotype Base Class Tags Constraints
«capsule» Class language
isActive = true;
self.feature->select(f | f.oclIsKindOf(Operation))-> forAll(o | o.elementOwnership.visibility = #protected)
Tag Stereotype Type Multiplicity
language «capsule» String 0..1
1.4
Advanced Modeling with UML 88
Stereotype Notation
Several choices
«capsule»«capsule»aCapsuleClassaCapsuleClass
«capsule»«capsule»aCapsuleClassaCapsuleClass aCapsuleClassaCapsuleClassaCapsuleClassaCapsuleClass
Stereotypeicon
Stereotypeicon
(a) with guillemets(a) with guillemets(“gwee-mays”)(“gwee-mays”)
(b) with icon(b) with icon
(c) iconified form(c) iconified form
Advanced Modeling with UML 89
Extensibility Method
Refinements are specified at the Model (M1) level but apply to the Meta-Model level (M2) avoids need for “meta-modeling” CASE tools can be exchanged with models
«Capsule»«Capsule»«Capsule»«Capsule»(M1)(M1)
(M2)(M2)ClassClassClassClass AssociationAssociationAssociationAssociation
CustomerOrderCustomerOrderCustomerOrderCustomerOrder
itemitemquantityquantityitemitemquantityquantity
CustomerCustomerCustomerCustomer
idididid
«capsule»«capsule»aCapsuleClassaCapsuleClass
«capsule»«capsule»aCapsuleClassaCapsuleClass
Advanced Modeling with UML 90
Graphical Definition
Alternative to the tabular form defined in a user (M1) model
«metaclass»
Class
«stereotype»
capsule
Tagslanguage : String
«stereotype»
1.4
Advanced Modeling with UML 91
Heuristic: Combining Stereotypes
Through multiple inheritance:
«stereotype»«stereotype»capsulecapsule
«stereotype»«stereotype»capsulecapsule
TagsTagslanguage : Stringlanguage : String
TagsTagslanguage : Stringlanguage : String
«metaclass»«metaclass»PackagePackage
«metaclass»«metaclass»PackagePackage
«stereotype»«stereotype»PackageCapsulePackageCapsule
«stereotype»«stereotype»PackageCapsulePackageCapsule
«stereotype»«stereotype»
1.4
Advanced Modeling with UML 92
When to Use Stereotypes?
Why not use normal subclassing instead?
Use stereotypes when: additional semantic constraints cannot
be specified through standard M1-level modeling facilities
e.g. “all features have protected visibility” the additional semantics have
significance outside the scope of UML e.g. instructions to a code generator
“debugOn = true”
Advanced Modeling with UML 93
Tagged Values
Consist of a tag and value pair Typed with a standard data type or M1
class name Typically used to model stereotype
attributes Additional information that is
useful/required to implement/use the model May also be used independently of
stereotypes e.g., project management data
(“status = unit_tested”)
1.4
Advanced Modeling with UML 94
Constrains Constraints
formal or informal expressions must not contradict inherited base semantics
ATM_WithdrawalATM_WithdrawalATM_WithdrawalATM_Withdrawal
customer : idcustomer : idamount : Moneyamount : Money{amount is multiple of $20}{amount is multiple of $20}
customer : idcustomer : idamount : Moneyamount : Money{amount is multiple of $20}{amount is multiple of $20}
AccountAccountAccountAccount
customer : idcustomer : idbalance : Moneybalance : Moneycustomer : idcustomer : idbalance : Moneybalance : Money
«constraint»«constraint»{ATM_Withdrawal.customer = {ATM_Withdrawal.customer = Account.customer}Account.customer}
«constraint»«constraint»{ATM_Withdrawal.customer = {ATM_Withdrawal.customer = Account.customer}Account.customer}
Advanced Modeling with UML 95
UML Profiles
A package of related extensibility elements that capture domain-specific variations and usage patterns A domain-specific interpretation of UML
Profiles currently being defined by the OMG: EDOC Real-Time CORBA ...
Advanced Modeling with UML 96
Advanced Modeling with UML
Part 1: Model Management Part 2: Extension Mechanisms and
Profiles Part 3: Object Constraint Language
(OCL)
Advanced Modeling with UML 97
Overview
What are constraints? Core OCL Concepts Advanced OCL Concepts Wrap up
Advanced Modeling with UML 98
Why use OCL ?
What’s in it for me?
Use the Object ConstraintLanguage
99
Can we make this more precise?
Flight Airplane
CargoFlightPassengerFlight
PassengerPlane CargoPlane11
0..*0..*11
0..*0..*
0..*0..*11flights
100
Diagram with added invariants
{context Flightinv: type = #cargo implies airplane.type = #cargoinv: type = #passenger implies airplane.type = #passenger}
10..*Flight Airplane
type : enum of cargo, passenger
type : enum of cargo, passenger
flights
Advanced Modeling with UML 101
Definition of constraint
“A constraint is a restriction on one or more values of (part of) an object-oriented model or system.”
Advanced Modeling with UML 102
Different kinds of constraints
Class invariant a constraint that must always be met
by all instances of the class Precondition of an operation
a constraint that must always be true BEFORE the execution of the operation
Postcondition of an operation a constraint that must always be true
AFTER the execution of the operation
Advanced Modeling with UML 103
Constraint stereotypes
UML defines three standard stereotypes for constraints: invariant precondition postcondition
Advanced Modeling with UML 104
What is OCL?
OCL is a textual language to describe
constraints the constraint language used in UML
models As well as the UML meta-model
Formal but easy to use unambiguous no side effects
Advanced Modeling with UML 105
Constraints and the UML model
OCL expressions are always bound to a UML model OCL expressions can be bound to any
model element in UML
Advanced Modeling with UML 106
Core OCL Concepts
What are constraints Core OCL Concepts Advanced OCL Concepts Wrap up
Advanced Modeling with UML 107
Example model
Airport
Flight
Passenger
Airline
*
**
*
$minAge: Integerage: IntegerneedsAssistance: Boolean
departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer
origin
desti-nation
name: String
name: String
{ordered}
arrivingFlights
departingFlights
CEO
0..1
flights
passengers
book(f : Flight)
0..1
airline
airline
Advanced Modeling with UML 108
Constraint context and self
Every OCL expression is bound to a specific context. The context is often the element that
the constraint is attached to The context may be denoted
within the expression using the keyword ‘self’. ‘self’ is implicit in all OCL expressions Similar to`this’ in C++
Advanced Modeling with UML 109
Notation
Constraints may be denoted within the UML model or in a separate document. the expression:
context Flight inv: self.duration < 4 is identical to:
context Flight inv: duration < 4 is identical to: Flight
duration: Integer<<invariant>>duration < 4
Advanced Modeling with UML 110
Elements of an OCL expression
In an OCL expression these elements may be used: basic types: String, Boolean, Integer,
Real. classifiers from the UML model and
their features attributes, and class attributes query operations, and class query
operations (i.e., those operations that do not have side effects)
associations from the UML model
Advanced Modeling with UML 111
Example: OCL basic types
context Airline inv:
name.toLower = ‘klm’
context Passenger inv:
age >= ((9.6 - 3.5)* 3.1).floor implies mature = true
Advanced Modeling with UML 112
Model classes and attributes
“Normal” attributes context Flight inv:
self.maxNrPassengers <= 1000
Class attributescontext Passenger inv:
age >= Passenger.minAge
Advanced Modeling with UML 113
Example: query operations
context Flight inv:
self.departTime.difference(self.arrivalTime) .equals(self.duration)
Time
difference(t:Time):Intervalbefore(t: Time): Booleanplus(d : Interval) : Time
Interval
equals(i:Interval):Boolean$Interval(d, h, m : Integer) :
Interval
$midnight: Timemonth : Stringday : Integeryear : Integerhour : Integerminute : Integer
nrOfDays : IntegernrOfHours : IntegernrOfMinutes : Integer
Advanced Modeling with UML 114
Associations and navigations
Every association in the model is a navigation path.
The context of the expression is the starting point.
Role names are used to identify the navigated association.
Advanced Modeling with UML 115
Example: navigations
context Flight
inv: origin <> destination
inv: origin.name = ‘Amsterdam’
context Flight
inv: airline.name = ‘KLM’
Airport
Flight
*
*
departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer
origin
desti-nation
name: String
arrivingFlights
departingFlights
Advanced Modeling with UML 116
Association classes
context Person inv:
if employer.name = ‘Klasse Objecten’ then
job.type = #trainer
else
job.type = #programmer
endif
Person Company
Job
* 1employee employer
type : {trainer, programmer}
name : String
Advanced Modeling with UML 117
The OCL Collection types
What are constraints Core OCL Concepts
Collections Advanced OCL Concepts Wrap up
Advanced Modeling with UML 118
Significance of Collections in OCL
Most navigations return collections rather than single elements
10..*Flight Airplane
type : enum of cargo, passenger
type : enum of cargo, passenger
flights
Advanced Modeling with UML 119
Three Subtypes of Collection
Set: arrivingFlights(from the context
Airport) Non-ordered, unique
Bag: arrivingFlights.duration (from the
context Airport) Non-ordered, non-unique
Sequence: passengers (from the context Flight) Ordered, non-unique
Advanced Modeling with UML 120
Collection operations
OCL has a great number of predefined operations on the collection types.
Syntax: collection->operation
Use of the “->” (arrow) operator instead of the“.” (dot) operator
Advanced Modeling with UML 121
The collect operation
Syntax:collection->collect(elem : T | expr)
collection->collect(elem | expr)
collection->collect(expr) Shorthand:
collection.expr The collect operation results in the
collection of the values resulting evaluating expr for all elements in the collection
Shorthand often trips people up. Be Careful!
Advanced Modeling with UML 122
Example: collect operation
context Airport inv:self.arrivingFlights -> collect(airLine) -
>notEmpty
airp1
airp2
f1
f2
f3
f4
f5
airline1
airline2
airline3
departing flights arriving flights
Advanced Modeling with UML 123
The select operation
Syntax:collection->select(elem : T | expression)
collection->select(elem | expression)
collection->select(expression)
The select operation results in the subset of all elements for which expression is true
Advanced Modeling with UML 124
Example: collect operation
context Airport inv:self.departingFlights->select(duration<4)-
>notEmpty
departing flights
arriving flights
airp1
airp2
airline1
airline2
airline3
f5duration = 2
f1duration = 2
f4duration = 5
f2duration = 5
f3duration = 3
Advanced Modeling with UML 125
The forAll operation
Syntax: collection->forAll(elem : T | expr) collection->forAll(elem | expr) collection->forAll(expr)
The forAll operation results in true if expr is true for all elements of the collection
Advanced Modeling with UML 126
Example: forAll operation
context Airport inv:self.departingFlights->forAll(departTime.hour>6)
departing flights arriving flights
airp1
airp2
airline1
airline2
airline3
f5depart = 8
f1depart = 7
f4depart = 9
f2depart = 5
f3depart = 8
Advanced Modeling with UML 127
The exists operation
Syntax:collection->exists(elem : T | expr)
collection->exists(elem | expr)
collection->exists(expr)
The exists operation results in true if there is at least one element in the collection for which the expression expr is true.
Advanced Modeling with UML 128
Example: exists operation
context Airport inv:self.departingFlights-
>exists(departTime.hour<6)
departing flights arriving flights
airp1
airp2
airline1
airline2
airline3
f5depart = 8
f1depart = 7
f4depart = 9
f2depart = 5
f3depart = 8
Advanced Modeling with UML 129
Other collection operations isEmpty: true if collection has no elements notEmpty: true if collection has at least
one element size: number of elements in collection count(elem): number of occurences of
elem in collection includes(elem): true if elem is in collection excludes(elem): true if elem is not in
collection includesAll(coll): true if all elements of coll
are in collection
Advanced Modeling with UML 130
What are constraints Core OCL Concepts Advanced OCL Concepts Wrap up
Advanced OCL Concepts
Advanced Modeling with UML 131
Result in postcondition
Example pre and postcondition
context Airline::servedAirports() : Set(Airport)
pre : -- none
post: result = flights.destination->asSet
Advanced Modeling with UML 132
Statechart: referring to states
The operation oclInState returns true if the object is in the specified state.
open closed
context Bottle inv:self.oclInState(closed) implies filled = #full
Bottle
filled : enum {empty, half, full}
Advanced Modeling with UML 133
Local variables
The let construct defines variables local to one constraint:Let var : Type = <expression1> in
<expression2>
Example:context Airport inv:Let supportedAirlines : Set (Airline) =
self.arrivingFlights -> collect(airLine) in (supportedAirlines ->notEmpty) and (supportedAirlines ->size < 500)
Advanced Modeling with UML 134
Iterate
The iterate operation for collections is the most generic and complex building block.
collection->iterate(elem : Type; answer : Type = <value> |
<expression-with-elem-and-answer>)
Advanced Modeling with UML 135
Iterate example
Example iterate:context Airline inv:flights->select(maxNrPassengers > 150)->notEmpty
Is identical to:context Airline inv:flights->iterate (f : Flight;
answer : Set(Flight) = Set{ } |if f.maxNrPassengers > 150 then
answer->including(f)else
answer endif )->notEmpty
Advanced Modeling with UML 136
Inheritance of constraints
Guiding principle Liskov’s Substitution Principle (LSP): “Whenever an instance of a class is
expected, one can always substitute an instance of any of its subclasses.”
Advanced Modeling with UML 137
Inheritance of constraints
Consequences of LSP for invariants: An invariant is always inherited by
each subclass. Subclasses may strengthen the
invariant. Consequences of LSP for
preconditions and postconditions: A precondition may be weakened
(contravariance) A postcondition may be strengthened
(covariance)
Advanced Modeling with UML 138
What are constraints Core OCL Concepts Advanced OCL Concepts Wrap up
Wrap Up
Advanced Modeling with UML 139
Current Developments
Feedback from several OCL implementers handled in UML-RTF e.g. the grammar has some loose ends typical tool-related issues
Development of OCL metamodel currently concrete syntax only will result in abstract syntax
UML 2.0 RFP meta-model as part of the UML meta-
model additional capabilities (e.g., business rules)
Advanced Modeling with UML 140
OCL Tools
Cybernetics ww.cybernetic.org
University of Dresden www-st.inf.tu-dresden.de/ocl/
Boldsoft www.boldsoft.com
ICON computing www.iconcomp.com
Royal Dutch Navy Others … …
Advanced Modeling with UML 141
Conclusions and Tips
OCL invariants allow you to model more precisely remain implementation independent
OCL pre- and postconditions allow you to specify contracts (design by contract) specify interfaces of components more
precisely OCL usage tips
keep constraints simple always combine natural language with OCL use a tool to check your OCL
Advanced Modeling with UML 142
Further Resources for OCL
The Object Constraint Language ISBN 0-201-37940-6
OCL home page www.klasse.nl/ocl/index.htm
Advanced Modeling with UML 143
References
[UML 1.3] OMG UML Specification v. 1.3, OMG doc# ad/06-08-99
[UML 1.4] OMG UML Specification v. 1.4, UML Revision Task Force recommended final draft, OMG doc# ad/01-02-13.
Advanced Modeling with UML 144
Web: UML 1.4 RTF: www.celigent.com/omg/umlrtf OMG UML Tutorials: www.celigent.com/omg/umlrtf/tutorials.
htm UML 2.0 Working Group: www.celigent.com/omg/adptf/wgs
/uml2wg.htm OMG UML Resources: www.omg.org/uml/
Email uml-rtf@omg.org Contributors
Karin Palmkvist: karin.palmkvist@enea.se Bran Selic: bselic@rational.com Jos Warmer: j.warmer@klasse.nl Nathan Dykman: nathan_dykman@hp.com
Conferences & workshops UML World 2001, New York, June 11-14, 2001 UML 2001, Toronto, Canada, Oct. 1-5, 2001 OMG UML Workshop 2001, San Francisco, Dec. 3-6, 2001
Further Info