Upload
lamdan
View
229
Download
0
Embed Size (px)
Citation preview
Advanced Modeling
Karin Palmkvist, Bran Selic, and Jos Warmer
UML Revision Task ForceNovember 2000
© 1999-2000 OMG and Tutorial Contributors: EDS, IBM, Enea Data, InLine Software,IntelliCorp, Kabira Technologies, Klasse Objecten, ObjectTime Ltd., Rational Software, Unisys
Object Modeling with OMG UML Tutorial Series
Advanced Modeling with UML 2
Overview
! Tutorial series! UML Overview! Advanced Modeling
! Part 1: Model Management! Karin Palmkvist, Enea Data
! Part 2: Extension Mechanisms and Profiles! Bran Selic, Rational Software
! Part 3: Object Constraint Language (OCL)! Jos Warmer, Klasse Objecten
Advanced Modeling with UML 3
Tutorial Series! Lecture 1: Introduction to UML:
Structural Modeling and Use Cases! Lecture 2: Behavioral Modeling with
UML! Lecture 3: Advanced Modeling with UML! Lecture 4: Metadata Integration with
UML, MOF and XMI
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
UML Overview
Foundation
Model Management
Behavioral Elements
dependency
package
Advanced Modeling with UML 6
Foundation
Model Management
Behavioral Elements
UML Overview
CoreExtension Mechanisms
Data Types
Advanced Modeling with UML 7
Behavioral Elements
Model Management
Foundation
UML Overview
Use Cases State Machines Activity GraphsCollaborations
Common Behavior
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
UML Overview
Use Cases State Machines Activity Graphs
Behavioral Elements
Model Management
Foundation
Collaborations
Common Behavior
Advanced Modeling with UML 10
Model Management Overview
! Package! Subsystem! Model
Advanced Modeling with UML 11
Unifying Concepts
! Grouping - Packages, Subsystems, and Models all group other model elements, although with very differing purposes
! Other grouping elements include Classes and 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
! In particular, there can be a containment hierarchy of nested packages
! A package defines a namespace for its contents
! Packages can be used for different purposes
Advanced Modeling with UML 16
Core ConceptsConstruct 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
! 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 ‘-’
Advanced Modeling with UML 18
X Y
Import
The associations are owned by package X
«import»A
B +C-D
+E
A
B +C-D
+E
X Y
Y::C
Y::E«import»
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
-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
X Y Z
Import vs. Access
«import»
A
B +C-D
+E
«import»
+G
+F
-H-Z::G
+Z::F
«access»
A
B +C-D
+E
«access»
+G
+F
-H
Y::C
Y::E
Y::F
Advanced Modeling with UML 22
Diagram Tour
! Packages are shown in static diagrams! Two equivalent ways to show containment:
Advanced Modeling with UML 23
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 24
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” what is done to it in the imported package
Advanced Modeling with UML 25
Subsystem
! What are Subsystems?! Core Concepts! Diagram Tour! When to Use Subsystems! Modeling Tips
Advanced Modeling with UML 26
Subsystem
Subsystems are used for system decomposition
Advanced Modeling with UML 27
Subsystem – Example
TrunkTraffic Control
Subscription
Communicating subsystems constitute a system
Advanced Modeling with UML 28
Core Concepts
Subsystem
Construct Description SyntaxA grouping of model elements that represents a behavioral unit in a physical system.
Name
Advanced Modeling with UML 29
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 30
Subsystem Aspects
A subsystem has a specification and a realization
Realization elementsSpecification elements
Advanced Modeling with UML 31
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 32
Subsystem Specification
The subsystem specification defines the external view of the subsystem
Realization elementsSpecification elements
?
Advanced Modeling with UML 33
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 34
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 35
Use Case Approach
! For subsystem services used in certain sequences
! When the specification is to be understood by non-technical people
! For complex behavior
Realization elementsSpecification elements
Advanced Modeling with UML 36
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 37
State Machine Approach
Specification elements
Stopped Running
Error
Maintenance
Exhausted
Traffic Control
! For subsystems with state dependent behavior
! Focuses on the states of the subsystem and the transitions between them
Advanced Modeling with UML 38
Specification elements
AnalyzerNumber
Dictionary
Network Manager
Traffic Control
! When usage of the subsystem is perceived as manipulation of objects
! When the requirements are guided by a particular standard
Logical Class Approach
Advanced Modeling with UML 39
Operation Approach
OperationsinitiateConnection (…)dialledDigit (…)throughConnect (…)bAnswer (…)bOnHook (…)aOnHook (…)
Traffic Control
! For subsystems providing simple, “atomic” services! When the operations are invoked independently
Advanced Modeling with UML 40
Mixing TechniquesTraffic Control
changeDigitAnalysisInformation (...)
Operator
Initiate Call
Receive Digit and Connect
Hook Signal and DisconnectSubscription
Trunk
Specification elements
Specification elements
Operations
Advanced Modeling with UML 41
Complete Subsystem Notation
! The complete subsystem symbol has three pre-defined compartments
! Each of the compartments may be optionally omitted from the diagram
Realization elements
Specification elements
Operations
Advanced Modeling with UML 42
Subsystem Interfaces
TrunkTraffic Control Subscription
TrunkTraffic Control Subscription
Advanced Modeling with UML 43
Operations and Interfaces
The subsystem must support all operations in the offered interfaces
Operationsoperation1( ) : Type1
operation2( ) : Type2
operation3( ) : Type3
operation4( ) : Type4
operation5( ) : Type5
«Interface»
«realize»operation1( )operation2( )operation4( )
«Interface»
«realize»operation2( )operation3( )operation5( )
Advanced Modeling with UML 44
Subsystem Interfaces
Specification elements«Interface»
«realize»
«Interface»
«realize»
Advanced Modeling with UML 45
Specification – Realization
! The specification and the realization must be consistent
! The mapping between the specification and the realization can be expressed by:
! «realize» relationships! collaborations
Advanced Modeling with UML 46
Realize Relationship
«realize» is particularly useful in simple mappings
Operations
operation1( ) : Type1
operation2( ) : Type2
operation3( ) : Type3
operation4( ) : Type4
operation5( ) : Type5
Realization Elements
«realize»operation1( )
Advanced Modeling with UML 47
Realize – Example
Realization elements
Specification elements
changeDigitAnalysisInformation ( )
Initiate Call
Receive Digit and Connect
Hook Signal and DisconnectSubscription
Traffic Control
Operations
Operator
Trunk
changeDigitAnalysisInformation ( )::
«realize»
Advanced Modeling with UML 48
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 49
Collaboration – Notation
A collaboration and its participants
Collaboration
Role
Class
role name
role namerole name
role name
Advanced Modeling with UML 50
Collaboration – Example
Collaborations are useful in more complex situations
Specification elements Realization elements
Receive Digit and Connect
Hook Signal and Disconnect
Initiate Call
CoordinatorAnalysisDatabase
NetworkInterface
Advanced Modeling with UML 51
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 52
Diagram Tour – continued
! Subsystems can be shown in interaction diagrams! collaboration diagrams! sequence diagrams
Sequence Diagram
Advanced Modeling with UML 53
When to Use Subsystems
! To express how a large system is decomposed into smaller parts
! To express how a set of modules are composed into a large system
! To trace requirements between the system and its parts
Advanced Modeling with UML 54
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 55
Model
! What are Models?! Core Concepts! Diagram Tour! When to Use Models! Modeling Tips
Advanced Modeling with UML 56
Model
A model is an abstraction of a system, specifying the system from a certain viewpoint and at a certain level of abstraction
Advanced Modeling with UML 57
Model – Example
Design Model
Use Case Model
Advanced Modeling with UML 58
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»
An abstraction of a system, as seen from a specific viewpoint and at a certain level of abstraction and detail.
Name
Advanced Modeling with UML 59
Trace
Analysis
Design
«trace»
Advanced Modeling with UML 60
Diagram Tour
! Models as such are seldom shown in diagrams
! Two equivalent ways to show containment:
Advanced Modeling with UML 61
Model vs. DiagramUse Case Model
Design Model
Diagrams make up the documentation of a model
Advanced Modeling with UML 62
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 63
Modeling Tips – Model
! Define the purpose for each model! A model must give a complete picture of the
system, within its viewpoint and level of abstraction
! Focus on the purpose of the model; omit irrelevant information
Advanced Modeling with UML 64
Models and SubsystemsModels and subsystems can be combined in a
hierarchy:
Advanced Modeling with UML 65
Wrap Up Model Management! Packages are used to organize a large set of model
elements! Visibility! Import! Access
! Subsystems are used to structure a large system! Specification! Realization
! Models are used to show different aspects of a system! Trace
Advanced Modeling with UML 66
Advanced Modeling with UML
! Part 1: Model Management! Part 2: Extension Mechanisms and Profiles! Part 3: Object Constraint Language (OCL)
Advanced Modeling with UML 67
Semantic Variations in UML
! Semantic aspects that are:! undefined (e.g., scheduling discipline), or
! ambiguous (multiple interpretations/possibilities)
! Why?! Different domains require different specializations
! Extend the applicability and utility of UML to a very broad spectrum of domains
! …while avoiding the “PL/I syndrome”
Advanced Modeling with UML 68
Extensibility Mechanisms! Used for refining the general UML
semantics! must be consistent with general UML
semantics!
Purpose:To obtain specialized domain-specific or even application-specific variations of general-purpose modeling concepts
Standard UML semanticsStandard UML semanticsStandard UML semantics
refined semantics(valid)refined semanticsrefined semantics(valid)(valid) different semantics
(NOT valid)different semanticsdifferent semantics(NOT valid)(NOT valid)
Advanced Modeling with UML 69
Models! A model is a description of something
! “a pattern for something to be made” (Merriam-Webster)! model ≠ thing that is modeled
blueprint(model)
model ≠ thing that is modeledbuilding building
Advanced Modeling with UML 70
Meta-Models! Models of models (modeling tools)
ClassClassClass AssociationAssociationAssociation
ObjectsObjects
ModelModel
MetaMeta--ModelModel
(M0)(M0)
(M1)(M1)
(M2)(M2)
<sawdust><2 tons><sawdust><sawdust><2 tons><2 tons>
<Ben&Jerry’s><Ben&Jerry’s><Ben&Jerry’s> <lard><5 tons><lard><lard><5 tons><5 tons>
CustomerOrderCustomerOrderCustomerOrder
itemquantityitemitemquantityquantity
CustomerCustomerCustomer
ididid
Advanced Modeling with UML 71
The UML Meta-Model! Expressed using a very small subset of UML
GeneralizableElementGeneralizableElementGeneralizableElement
isRoot : BooleanisLeaf : BooleanisAbstract : Boolean
isRootisRoot : Boolean: BooleanisLeafisLeaf : Boolean: BooleanisAbstractisAbstract : Boolean: Boolean
ClassClassClass
isActive : BooleanisActiveisActive : Boolean: Boolean
ClassifierClassifierClassifier
FeatureFeatureFeature
visibility : {public, private,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)))
WellWell--formedness formedness constraint (OCL)constraint (OCL)
Meta-ClassMetaMeta--ClassClass
Advanced Modeling with UML 72
The Three Basic 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 73
Example: A Special Type of Class
ClassClassClass
isActive : BooleanisActiveisActive : Boolean: Boolean
self.feature->select(f |f.oclIsKindOf(Operation))-> forAll(o |
o.elementOwnership.visibility = #protected)
self.feature->select(f |f.oclIsKindOf(Operation))-> forAll(o |
o.elementOwnership.visibility = #protected)
«Capsule»«Capsule»«Capsule»
<Language = ”C++”><Language = ”C++”><Language = ”C++”>
Stereotypeconstraint
Stereotypeconstraint
Required tagRequired tagStereotypeStereotype
Advanced Modeling with UML 74
Extensibility Method! Refinements are specified at the Model (M1)
level but apply to the Meta-Model level (M2)! does not require “meta-modeling” CASE tools! can be exchanged with models
«Capsule»«Capsule»«Capsule»(M1)(M1)
(M2)(M2)ClassClassClass AssociationAssociationAssociation
CustomerOrderCustomerOrderCustomerOrder
itemquantityitemitemquantityquantity
CustomerCustomerCustomer
ididid
«capsule»aCapsuleClass
«capsule»«capsule»aCapsuleClassaCapsuleClass
Advanced Modeling with UML 75
Stereotypes! Used to define derivative modeling concepts
based on existing generic modeling concepts! Defined by:
! base (meta-)class = UML meta-class or stereotype! constraints! required tags (0..*)
! often used for modeling pseudo-attributes
! icon
! A model element can have at most one stereotype
Advanced Modeling with UML 76
Heuristic: Combining Stereotypes
! Through multiple inheritance:
«Capsule»«Capsule»«Capsule»
<Language = ”C++”><Language = ”C++”><Language = ”C++”>
«Square»«Square»«Square»
«SquareCapsule»««SquareCapsuleSquareCapsule»»
Advanced Modeling with UML 77
Stereotype Notation! Several choices
«capsule»aCapsuleClass
«capsule»«capsule»aCapsuleClassaCapsuleClass aCapsuleClassaCapsuleClassaCapsuleClass
Stereotypeicon
Stereotypeicon
(a) with (a) with guillemetsguillemets (b) with icon(b) with icon
(c) (c) iconified iconified formform
Advanced Modeling with UML 78
Heuristic: When to Stereotype?! Abstract class or stereotype?
ClassClassClassisActive : BooleanisActiveisActive : Boolean: Boolean
«Capsule»«Capsule»«Capsule»<Language = ”C++”><Language = ”C++”><Language = ”C++”>
AbstractCapsuleClass
AbstractCapsuleAbstractCapsuleClassClass
«capsule»aCapsuleClass
«capsule»«capsule»aCapsuleClassaCapsuleClass
Stereotypes typically used where one or more tools need to support (validate, enforce) the supplementary semantics
basis for further standardization
Advanced Modeling with UML 79
Tagged Values and Constraints! Tagged values:
! consist of a tag and value pair! often used to model stereotype attributes! arbitrary domain-specific semantics
! instructions to a code generator (“debug_flag = true”)! project management data (“status = unit_tested”)! etc.
! Constraints! formal or informal expressions! must not contradict inherited base semantics
Advanced Modeling with UML 80
Constraint Notation! Enclosed in braces “{…}”! Can appear in various places in a model
ATM_WithdrawlATM_ATM_WithdrawlWithdrawl
customer : idamount : Money{amount is multiple of $20}
customer : idcustomer : idamount : Moneyamount : Money{amount is multiple of $20}{amount is multiple of $20}
AccountAccountAccount
customer : idbalance : Moneycustomer : idcustomer : idbalance : Moneybalance : Money
{ATM_Withdrawl.customer = Account.customer}
{ATM_{ATM_WithdrawlWithdrawl.customer = .customer = Account.customer}Account.customer}
Advanced Modeling with UML 81
UML Profiles! A package of related specializations of
general UML concepts 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 82
Advanced Modeling with UML
! Part 1: Model Management! Part 2: Extension Mechanisms and Profiles! Part 3: Object Constraint Language (OCL)
Advanced Modeling with UML 83
Overview! What are constraints?! Core OCL Concepts! Advanced OCL Concepts! Wrap up
Advanced Modeling with UML 84
Why use OCL ?What’s in it
for me?
Use the Object ConstraintLanguage
85
That’s why !!
Flight Airplane
CargoFlightPassengerFlight
PasssengerPlane CargoPlane11
0..*0..* 11
0..*0..*
0..*0..*11flights
86
Diagram with invariants
context Flightinv: type = #cargo implies airplane.type = #cargoinv: type = #passenger implies airplane.type = #passenger
10..*Flight Airplane
type = enum{cargo, passenger}
type = enum{cargo, passenger}
flights
Advanced Modeling with UML 87
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 88
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 89
Constraint stereotypes! UML defines three standard stereotypes
for constraints:! invariant! precondition! postcondition
Advanced Modeling with UML 90
What is OCL?! OCL is
! a textual language to describe constraints! the constraint language of the UML
! Formal but easy to use ! unambiguous! no side effects
Advanced Modeling with UML 91
Constraints and the UML model! OCL expressions are always bound to a
UML model
Advanced Modeling with UML 92
Overview! What are constraints! Core OCL Concepts! Advanced OCL Concepts! Wrap up
Advanced Modeling with UML 93
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 94
Constraint context and self! Every OCL expression is bound to a
specific context.! The context may be denoted within the
expression using the keyword ‘self’.Who? Who? Me?Me?
Advanced Modeling with UML 95
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 96
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
! associations from the UML model
Advanced Modeling with UML 97
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 98
Model classes and attributes! “Normal” attributes
context Flight inv:self.maxNrPassengers <= 1000
! Class attributescontext Passenger inv:age >= Passenger.minAge
Advanced Modeling with UML 99
Example: query operationscontext 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 100
Associations and navigations! Every association 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 101
Example: navigations! Navigations
context Flightinv: origin <> destinationinv: origin.name = ‘Amsterdam’
context Flight inv: airline.name = ‘KLM’
Advanced Modeling with UML 102
Association classescontext Person inv:if employer.name = ‘Klasse Objecten’ then
job.type = #trainerelse
job.type = #programmerendif
Person Company
Job
* 1employee employer
type : {trainer, programmer}
name : String
Advanced Modeling with UML 103
The OCL Collection types! What are constraints! Core OCL Concepts
! Collections
! Advanced OCL Concepts! Wrap up
Advanced Modeling with UML 104
Three subtypes to Collection! Set:
! arrivingFlights(from the context Airport)
! Bag: ! arrivingFlights.duration (from the context
Airport)
! Sequence: ! passengers (from the context Flight)
Advanced Modeling with UML 105
Collection operations! OCL has a great number of predefined
operations on the collections types.
! Syntax:
collection->operation
Advanced Modeling with UML 106
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
Advanced Modeling with UML 107
Example: collect operationcontext 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 108
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 109
Example: collect operationcontext 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 110
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 111
Example: forAll operationcontext 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 112
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 113
Example: exists operationcontext 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 114
Example: exists operationcontext Airport inv:self.departingFlights ->
exists(departTime.hour < 6)
Advanced Modeling with UML 115
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 116
Result in postcondition! Example pre and postcondition
context Airline::servedAirports() : Set(Airport)pre : -- nonepost: result = flights.destination->asSet
Advanced Modeling with UML 117
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
Bottlefilled : enum {empty, half, full}
Advanced Modeling with UML 118
Local variables! The Let construct defines variables local
to one constraint:
Let var : Type = <expression1> in <expression2>
Advanced Modeling with UML 119
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 120
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 121
Inheritance of constraints! Guiding principle Liskovs 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 122
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! A postcondition may be strengthened
Advanced Modeling with UML 123
Wrap up! What are constraints! Core OCL Concepts! Advanced OCL Concepts! Wrap up
Advanced Modeling with UML 124
Current Developments! Feedback from several OCL
implementors 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
! OCL Workshop with pUML group! formalization of OCL
Advanced Modeling with UML 125
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 126
Conclusions and Tips! OCL invariants allow you to
! model more precisely! stay implementation independent
! OCL pre- and postconditions allow you to! specify contracts (design by contract)! precisely specify interfaces of components
! OCL usage tips! keep constraints simple! always combine natural language with OCL! use a tool to check your OCL
Advanced Modeling with UML 127
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 128
Preview - Next Tutorial
! Metadata Integration with UML, MOF and XMI! OMG Modeling and Metadata Architecture! Meta Object Facility (MOF)! XML Metadata Interchange (XMI)
Advanced Modeling with UML 129
! 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! Karin Palmkvist: [email protected]! Bran Selic: [email protected]! Jos Warmer: [email protected]
! Conferences & workshops! OMG UML Workshop: UML in the .com Enterprise, Palm Springs,
California, Nov. 2000! UML World 2001, location and dates TBA! UML 2001, Toronto, Canada, Oct. 2001
Further Info