Title: OCL
1OCL The Object Constraint Language in UML
OCL website http//www.omg.org/uml/ Textbook
The Objection Constraint Language Precise
Modeling with UML, by Jos Warmer and Anneke
Kleppe This presentation includes some slides by
Yong He, Tevfik Bultan, Brian Lings, Lieber. The
Summary is based on UML and its Meaning, by
P.H. Schmitt
2History
- First developed in 1995 as IBEL by IBMs
Insurance division for business modelling - IBM proposed it to the OMGs call for an
object-oriented analysis and design standard. OCL
was then merged into UML 1.1. - OCL was used to define further upgrades of UML.
3Companies behind OCL
- Rational Software, Microsoft, Hewlett-Packard,
Oracle, Sterling Software, MCI Systemhouse,
Unisys, ICON Computing, IntelliCorp, i-Logix,
IBM, ObjecTime, Platinum Technology, Ptech,
Taskon, Reich Technologies, Softeam
4UML Diagrams are NOT Enough!
- We need a language to help with the spec.
- We look for some add-on instead of a brand new
language with full specification capability. - Why not first order logic? Not OO.
- OCL is used to specify constraints on OO systems.
- OCL is not the only one.
- But OCL is the only one that is standardized.
5OCL fills the missing gap
- Formal specification language ? implementable.
- Supports object concepts.
- Intuitive syntax reminds OO programming
languages. - But OCL is not a programming language
- No control flow.
- No side-effects.
6Advantages of Formal Constraints
- Better documentation
- Constraints add information about the model
elements and their relationships to the visual
models used in UML - It is way of documenting the model
- More precision
- OCL constraints have formal semantics, hence, can
be used to reduce the ambiguity in the UML models - Communication without misunderstanding
- UML models are used to communicate between
developers, Using OCL constraints modelers can
communicate unambiguously
7Where to use OCL?
- Specify invariants for classes and types
- Specify pre- and post-conditions for methods
- As a navigation language
- To specify constraints on operations
- Test requirements and specifications
- Following
- OCL by example short.
- OCL summary in some detail.
8Example A Mortgage System
- A person may have a mortgage only on a house
he/she owns.The start date of a mortgage is
before its end date.
9OCL specification of the constraints
1. context Mortgage context Mortgage
invariant self.security.owner self.borrower
invariant security.owner borrower2. context
Mortgage context Mortgage invariant
self.startDate lt self.endDate invariant
startDate lt endDate
10More Constraints Examples
- All players must be over 18.
- The number of guests in each room doesnt exceed
the number of beds in the room.
Player
context Player invariant self.age gt18
age Integer
Room
room
guests
Guest
numberOfBeds Integer
context Room invariant guests -gt size lt
numberOfBeds
11Constraints (invariants), Contexts and Self
- A constraint (invariant) is a boolean OCL
expression evaluates to true/false. - Every constraint is bound to a specific type
(class, association class, interface) in the UML
model its context. - The context objects may be denoted within the
expression using the keyword self. - The context can be specified by
- Context ltcontext namegt
- A dashed note line connecting to the context
figure in the UML models - A constraint might have a name following the
keyword invariant.
12Example of a static UML Model
- Problem story
- A company handles loyalty programs (class
LoyaltyProgram) for companies (class
ProgramPartner) that offer their customers
various kinds of bonuses. Often, the extras take
the form of bonus points or air miles, but other
bonuses are possible. Anything a company is
willing to offer can be a service (class Service)
rendered in a loyalty program. Every customer can
enter the loyalty program by obtaining a
membership card (class CustomerCard). The objects
of class Customer represent the persons who have
entered the program. A membership card is issued
to one person, but can be used for an entire
family or business. Loyalty programs can allow
customers to save bonus points (class
loyaltyAccount) , with which they can buy
services from program partners. A loyalty account
is issued per customer membership in a loyalty
program (association class Membership).
Transactions (class Transaction) on loyalty
accounts involve various services provided by
the program partners and are performed per single
card. There are two kinds of transactions
Earning and burning. Membership durations
determine various levels of services (class
serviceLevel).
13LoyaltyProgram
Customer
1..
name String titleString isMale
Boolean dateOfBirth Date
0..
0..
partners
1..
enroll(cCustomer)
program
ProgramPartner
1
0..
numberOfCustomers Integer
Membership
age() Integer
1
1
partner
owner
ordered
1..
actualLevel
1
1
0..1
card
0..
ServiceLevel
card
LoyaltyAccount
CustomerCard
name String
1
0..
deliveredServices
points Integer
1
level
valid Boolean validForm Date goodThru
Date color enumsilver,
gold printedName String
earn(i Integer) burn(i Integer) isEmpty()
Boolean
Service
0..
condition Boolean pointsEarned
Integer pointsBurned Integer description String
availableServices
account
1
0..
transactions
Transaction
card
generatedBy
points Integer dateDate
1
0..
1
Date
0..
transactions
now Date
transactions
program() LoyaltyProgram
isBefore(tDate) Boolean isAfter(tDate)
Boolean (tDate) Boolean
Burning
Earning
14Using OCL in Class Diagrams
LoyaltyAccount
class invariant
points Integer
points gt 0
earn(i Integer) burn(i Integer) isEmpty()
Boolean
ltltpreconditiongtgt i gt 0
ltltpreconditiongtgt points gt i and i gt 0
precondition for burn operation
ltltpostconditiongtgt points points_at_pre i
ltltpostconditiongtgt points points_at_pre - i
ltltpostconditiongtgt result (points0)
postcondition for burn operation
15Invariants on Attributes
- Invariants on attributes
- context Customer
- invariant agerestriction age gt 18
- context CustomerCard
- invariant correctDates validFrom.isBefore(goodThr
u) - The type of validFrom and goodThru is Date.
- isBefore(Date)Boolean is a Date operation.
- The class on which the invariant must be put is
the invariant context. - For the above example, this means that the
expression is an invariant of the Customer class.
16Invariants using Navigation over Association Ends
Roles (1)
- Navigation over associations is used to refer to
associated - objects, starting from the context object
- context CustomerCard
- invariant owner.age gt 18
- owner ? a Customer instance.
- owner.age ? an Integer.
- Note This is not the right context for this
constraint! - If the role name is missing use the class name
at the other - end of the association, starting with a lowercase
letter. - Preferred Always give role names.
17Invariants using Navigation over Association Ends
Roles (2)
- context CustomerCard
- invariant printedName
- printedName
- owner.title.concat( ).concat(owner.name)
- printedName ? a String.
- owner ? a Customer instance.
- owner.title ? a String.
- owner.name ? a String.
- String is a recognized OCL type.
- concat is a String operation, with the signature
concat(String) String.
18Invariants using Navigation from Association
Classes
Navigation from an association class can use the
classes at the association class end, or the role
names. The context object is the association
class instance a tuple. The owner of the card
of a membership must be the customer in the
membership context Membership invariant
correctCard card.owner customer
19Invariants using Navigation through Association
Classes
Navigation from a class through an association
class uses the association class name to obtain
all tuples of an object The cards of the
memberships of a customer are only the
customers cards context Customer invariant
correctCard cards-gtincludesAll(Membership.card)
This is exactly the same as the previous
constraint The owner of the card of a
membership must be the customer in the
membership context Membership invariant
correctCard card.owner customer The
Membership correctCard constraint is better!
20Invariants using Navigation through Associations
with Many Multiplicity
- Navigation over associations roles with
multiplicity greater than - 1 yields a Collection type. Operations on
collections are - accessed using an arrow -gt, followed by the
operation name. - A customer card belongs only to a membership of
its owner - context CustomerCard
- invariant correctCard
- owner.Membership-gtincludes(membership)
- owner ? a Customer instance.
- owner.Membership ? a set of Membership instances.
- membership ? a Membership instance.
- includes is an operation of the OCL Collection
type.
21Navigating to collections
Customer
Account
Transaction
0..
0..
context Customeraccount produces a
set of Accounts context Customer
account.transaction produces a bag of
transactions If we want to use this as a set we
have to do the following account.transaction -gt
asSet
22Navigation to Collections
The partners of a loyalty program have at
least one delivered service context
LoyaltyProgram invariant minServices
partners.deliveredservices-gtsize() gt 1 The
number of a customers programs is equal to that
of his/her valid cards context
Customer invariant sizesAgree Programs-gtsize()
cards-gtselect(validtrue)-gtsize()
23Navigation to Collections
When a loyalty program does not offer the
possibility to earn or burn points, the members
of the loyalty program do not have loyalty
accounts. That is, the loyalty accounts
associated with the Memberships must be empty
context LoyaltyProgram invariant noAccounts
partners.deliveredservices-gt forAll(pointsEarned
0 and pointsBurned 0) implies
Membership.account-gtisEmpty() and, or, not,
implies, xor are logical connectives.
24The OCL Collection types
- Collection is a predefined OCL type
- Operations are defined for collections
- They never change the original
- Three different collections
- Set (no duplicates)
- Bag (duplicates allowed)
- Sequence (ordered Bag)
- With collections type, an OCL expression either
states a fact about all objects in the collection
or states a fact about the collection itself,
e.g. the size of the collection. - Syntax
- collection-gtoperation
25Collection Operations
- ltcollectiongt ? size
- ? isEmpty
- ? notEmpty
- ? sum ( )
- ? count ( object )
- ? includes ( object )
- ? includesAll ( collection )
26Collections cont.
- ltcollectiongt ? select ( eT ltb.e.gt)
- ? reject ( eT ltb.e.gt)
- ? collect ( eT ltv.e.gt)
- ? forAll ( eT ltb.e.gt)
- ? exists ( eT ltb.e.gt)
- ? iterate ( eT1 rT2 ltv.e.gt ltv.e.gt)
- b.e. stands for boolean expression
- v.e. stands for value expression
27Changing the context
Customer
StoreCard
printNameString points Integer
nameString title String golduser Boolean
1..
owner
cards
earn(pInteger)
age( )Integer
context StoreCard invariant printName
owner.title.concat(owner.name) context
Customer cards ? forAll ( printName
owner.title.concat(owner.name) )
28Example UML diagram
Student
Module
0..
1..
taken
taken_by
code String credit Integer
name String
0..
submitted_by
for_module
set_work
1..
Assessment
submited
1..
weight Integer
Exam
Coursework
hours Integer
date String
29Constraints
- Modules can be taken iff they have more than
seven students registered - The assessments for a module must total 100
- Students must register for 120 credits each year
- Students must take at least 90 credits of CS
modules each year - All modules must have at least one assessment
worth over 50 - Students can only have assessments for modules
which they are taking
30Constraint (a)
- Modules can be taken iff they have more than
seven students registered - Note when should such a constraint be imposed?
- context Module
- invariant taken_by?size() gt 7
31Constraint (b)
- The assessments for a module must total 100
- context Module
- invariant
- set_work.weight?sum( ) 100
32Constraint (c)
- Students must register for 120 credits each year
- context Student
- invariant taken.credit?sum( ) 120
33Constraint (d)
- Students must take at least 90 credits of CS
modules each year - context Student
- invariant
- taken?
- select(code.substring(1,2) CS).credit?sum( )
gt 90
34Constraint (e)
- All modules must have at least one assessment
worth over 50 - context Module
- invariant set_work?exists(weight gt 50)
35Constraint (f)
- Students can only have assessments for modules
which they are taking - context Student
- invariant taken?includesAll(submited.for_module)
36Invariants using Navigation through Cyclic
Association Classes
- Navigation through association classes that are
- cyclic requires use of roles to distinguish
between - association ends
- object.associationClassrole
- The accumulated score of an employee is positive
- context Person
- invariant
- employeeRankingbosses.score-gtsum()gt0
- Every boss must give at least one 10 score
- context Person
- invariant
- employeeRankingemployees-gtexists(score 10)
Person
bosses
employees
EmploymentRanking
score
37Invariants using Navigation through Qualified
Association
- To navigate qualified associations you need to
index the qualified association using a qualifier - object.navigationqualifierValue, ...
- If there are multiple qualifiers their values are
separated using commas - Example
- context LoyaltyProgram
- serviceLevel1.name basic
- context LoyaltyProgram
- serviceLevel-gtexists(name basic)
LoyaltyProgram
enroll(cCustomer)
levelNumber Integer
0..1
ServiceLevel
name String
38Classes and Subclasses
- Consider the following constraint
- context LoyaltyProgram
- invariant
- partners.deliveredServices.transaction.points-gtsum
() lt 10,000 - If the constraint applies only to the Burning
subclass, we can use the operation oclType of
OCL - context LoyaltyProgram
- invariant
- partners.deliveredServices.transaction
- -gtselect(oclType Burning).points-gtsum() lt
10,000
39Classes and Subclasses
- The target of a dependency is not its source
- context Dependency
- invariant self.source ltgt self
- Is ambiguous
- Dependency is both
- a ModelElement and an Association class.
- context Dependency
- invariant self.oclAsType(Dependency).source ltgt
self - invariant
- self.oclAsType(ModelElement).source -gt
isEmpty()
source
target
ModelElement
Note
Dependency
40Combining UML and OCL
- Without OCL expressions, the model would be
severely underspecified - Without the UML diagrams, the OCL expressions
would refer to non-existing model elements, - there is no way in OCL to specify classes and
associations. - Only when we combine the diagrams and the
constraints can we completely specify the model.
41OCL Summary in some detail
- Contexts
- Types
- The allInstances operation.
- Collection operations
- Quantifiers
- Hierarchy
421. Contexts
- Two basic context modes
- The classifier context.
- The operator context.
431. Contexts Classifier context
- context ( c )? typeName
- inv expressionName1? OclExpression1
- . . .
- . . .
- inv expressionNamen? OclExpressionn
- All OclExpressions are boolean!
- l
441. Contexts Operator context
- context ( c )? typeName opName(p1 type1 . .
. - pk typek )rtype
- pre,post expressionName1? OclExpression1
-
-
- pre,post expressionNamen? OclExpressionn
- All OclExpressions are boolean!
- l
451. Contexts examples
context Paper inv self .number gt 1 context
cPaper inv c.number gt 1 context cPaper inv
startCount c.number gt 1 context Paper inv
startCount number gt 1
- context cPaperevaluate()
- pre c.status submitted
- post c.status accept or c.status reject
461. Contexts Operator contract
- Pre- and postconditions are seen as part of a
contract. - The method agrees that after its execution the
postcondition is true. - It is the obligation of the caller of a method to
ensure that the precondition holds. - The OCL standard does not make any commitment
what should happen, when the contract is broken.
47OCL Constraints
- A constraint is a restriction on one or more
values of (part of) an object model/system. - Constraints come in different forms
- invariant
- constraint on a class or type that must always
hold - pre-condition
- constraint that must hold before the execution of
an op. - post-condition
- constraint that must hold after the execution of
an op. - guard
- constraint on the transition from one state to
another.
48OCL Expressions and Constraints
- Each OCL expression has a type.
- Every OCL expression indicates a value or object
within the system. - 13 is a valid OCL expression of type Integer,
which represents the integer value 4. - An OCL expression is valid if it is written
according to the rules (formal grammar) of OCL. - A constraint is a valid OCL expression of type
Boolean.
492. Types
- OCL is a typed language.
- Every expression has a uniquely determined type.
- The syntax of expressions is restricted by typing
rules. - Main types
- 1. Model types
- Every class from the context diagram of an OCL
constraint is a type. - 2. Basic types
- There are 4 basic OCL types Integer, Real,
Boolean and String - 3. Enumeration types
- These are user dened types.
- 4. Collection types
- The collection types in OCL are Set, Bag,
Sequence. - 5. Special types
- Built in tricky OCL types. OclAny is a special
type.
502. Types Subtyping
For type expressions T1 T2 the direct subtype
relation T1 lt T2 is 1. If T1 T2 are model types
then T1 lt T2 holds exactly when in the context
UML diagram T1 is a subclass of T2. 2. Integer lt
Real 3. For all type expressions T, not denoting
a collection type, (a) Set(T) lt
Collection(T) (b) Bag(T) lt Collection(T) (c)
Sequence(T) lt Collection(T) 4. If T is a model,
basic or enumeration type then T lt OCLAny 5. If
T1 lt T2 and C is any of the type constructors
Collection, Set, Bag, Sequence, then C(T1) lt
C(T2). The subtype relation ltlt is the
transitive, reflexive closure of the direct
subtype relation lt. Also termed T1 conforms to T2.
512. Types
- Collections are not nested Nested collections
are flattened - Set(Set(T)) ? Set(T)
- Bag(Set(T)) ? Bag(T)
- Sequence(Set(T)) ? Sequence(T)
(non-deterministic). - If T is a type expression that this not a
collection type then Collection(T), Set(T),
Bag(T), Sequence(T) are also type expressions. - Types denote sets of objects.
- OCLAny denotes the set of all model, basic or
enumeration types (not including collections).
523. The allInstances operation
- allInstances is an operation on the predefined
OCL type OclType. - If C a class symbol then C.allInstances evaluates
to the set of all instances of class C. - OclType is the set of all types in a given
context.
Paper numbering is unique context Paper inv
Paper.allInstances -gtforAll(p1, p2 j p1 ltgt p2
implies p1.number ltgt p2.number)
533. The allInstances operation
- allInstances should be avoided if possible
(like class level (static) attributes or
operations in OO modeling).
Paper numbering is unique context
Conference inv self.submitted papers
-gtforAll(p1, p2 j p1 ltgt p2 implies p1.number ltgt
p2.number)
544. Collection operations iterate
- sumpages is the sum of the number of pages taken
over all papers
context pPapers inv Papers.allInstances -gt
iterate(xPaper yInt 0 yx.pages)
Papers.totalnumber
554. Collection operations iterate
- sumpages is the sum of the number of pages taken
over all papers
context pPapers inv Papers.allInstances -gt
iterate(xPaper yInt 0 yx.pages)
Papers.totalnumber
564. Collection operations iterate
- General form
- X, y are different.
- T does not contain y.
- T0 does not contain x or y.
- Evaluation
- Evaluate t and t0 in that order, and assign t0s
value to y. - For every element a of t
- Evaluate u with xa, y its current value (t0 in
the beginning) - Assign y value of u.
- Expression value is value of y after the
iteration.
574. Collection operations iterate
String operation Compute all occurrences
(beginnings) of string in string. Operation
occurrences The set of positions in string where
an occurrence of string as a substring starts.
Strings start with position 0. context string
Stringoccurences(stringString)Set(Integer) p
re string.size() lt string.size() post
result 0 .. (string.size() string.size())
-gt iterate(x y if
string.substring(x,xstring.size()-1)
string then y -gt including(x) else y)
584. Collection operations iterate
- Most collection operations can be expressed using
iterate. - forAll
- t -gt forAll(x a)
- where t is of type Set(T), x of type T, a is a
Boolean - Can be expressed by
- t -gt iterate(x y Boolean true y and a)
- where y does not occur in a.
594. Collection operations collect
60What is OCL Anyway?
- A textual specification language
- An expression language
- Is side-effect-free language
- Standard query language
- Is a strongly typed language
- so expressions can be precise
- Is a formal language
- Is part of UML
- Is used to define UML
- Is Not a programming language
- The OCL is declarative rather than imperative
- Mathematical foundation, but no mathematical
symbols - based on set theory and predicate logic
- has a formal mathematical semantics
61What did People Say?
- OCL is too implementation-oriented and therefore
not well-suited for conceptual modeling.
Moreover, it is at times unnecessarily verbose,
far from natural language. - Alloy modeling language.
- The use of operations in constraints appears to
be problematic. - An operation may go into an infinite loop or be
undefined. - Not stand alone language.
- OCL is a local expression (Mandana and Daniel).
- I would rather use plain English (Martin Fowler).
62References
- The Amsterdam Manifesto on OCL
- In Object Modeling with the OCL (LNCS2263)
p115-149 - The Object Constraint Language, Precise Modeling
with UML, Addison-Wesley, 1999. - The Object Constraint Language, Precise Modeling
with UML 2nd - Response to the UML 2.0 OCL RfP (ad/2000-09-03)
Revised Submission, Version 1.6 January 6, 2003 - Some Shortcomings of OCL, the Object Constraint
Language of UML - Mandana Vaziri and Daniel Jackson,1999
- http//www.klasse.nl/english/uml/ UML CENTER
- Informal formality? The Object Constraint
Language and its application in the UML metamodel
- Anneke Kleppe, Jos Warmer, Steve Cook
- A Pratical Application of the Object Constraint
Language OCL - Kjetil Mage
- The UML's Object Constraint Language OCL
Specifying Components, JAOO Tutorial September
2000 - Jos Warmer Anneke Kleppe