megaplanet
OCL : An Expression LanguageOCL : An Expression Language
Basic Types, Enumerated Types, Types ConstructorsBasic Types, Enumerated Types, Types Constructors
Expressions, OperationsExpressions, Operations
Operations on collectionsOperations on collections
megaplanet
2
OCL = An Expression LanguageOCL = An Expression Language
No side effectNo side effect
No explicit iterationNo explicit iteration
Like a functional languageLike a functional language
but no functions (in the standard)but no functions (in the standard)
Can serve as aCan serve as a query languagequery language
This first part,
« OCL : An Expression language » is
almost independent from UML
megaplanet
3
TypesTypes
Basic typesBasic types
IntegerInteger
RealReal
BooleanBoolean
StringString
Enumerated typesEnumerated types
MetatypesMetatypes
OclTypeOclType
OclAnyOclAny
OclStateOclState
OclExpressionOclExpression
Types from UMLTypes from UML
classesclasses
associationsassociations
……
Type constructorsType constructors
TupleType( x : T, y : T … )TupleType( x : T, y : T … )
Set(T)Set(T)
OrderedSet(T)OrderedSet(T)
Sequence(T)Sequence(T)
Bag(T)Bag(T)
Collection(T)Collection(T)
megaplanet
4
Syntax of ExpressionsSyntax of Expressions (Simplified)
<const> 12 'hello'
<id> children Residence
<expr> <op> <expr> age>18
self like in python, « this » in java
<exprobj> . <prop> self.chairman.age
<exprobj> . <objprop>(<expr>...) self.chairman.increaseSalary(10)
<exprcoll> -> <collprop>(<expr>...) self.employees->collect(salary)
<package>::<package> … :: <element> like in C++, « . » in python and java
if <expr> then <expr> else <expr> endif if age>18 then 1200 else 50*age endif
let <id> : <type> in <expr> .<expr> let e=x*x+y in (e-20)*1,5
megaplanet
5
ExamplesExamples
self.salary - 100
self.children->isEmpty()
self.children->forall(age>20)
self.getTaxes(1998) / self.children->size()
self.children->select( sex= Sex::male )
self.children->collect(salary)->sum()
self.children.salary->sum()
self.children->union(self.parents)->collect(age)
children
*
Person
sex:Sex
salary:real
age:integer
parents
0..2
getTaxes()
<<enumeration>>
Sex
male
female
megaplanet
6
To be Remembered !To be Remembered !
. to get access to properties of objects
->-> to get access to properties of collectionsto get access to properties of collections
+ some rules to mix collections and objects (see later)
self.taxes(1998) / self.children -> size()
because self
is an object
because self.children
is a collection of objects
megaplanet
7
Integer et RealInteger et Real
IntegerInteger
values :values : 1, -5, 34, 243431, -5, 34, 24343, ..., ...
operations :operations : +, -, *, div, mod, abs, max, min+, -, *, div, mod, abs, max, min
RealReal
values :values : 1.5, 1.341.5, 1.34, ..., ...
operations :operations : +, -, *, /, floor, round, max, min+, -, *, /, floor, round, max, min
Integer type « conforms » to the type Real
megaplanet
8
BooleanBoolean
BooleanBoolean
values :values : truetrue,, falsefalse
operations :operations : notnot,, andand,, oror,, xorxor,, impliesimplies,, if-then-else-endifif-then-else-endif
partial evaluation :partial evaluation :
true oror x always true, even when x is undefined
false andand x always false, even when x is undefined
(age<40 implies salaire>1000) and (age>=40 implies salaire>2000)
if age<40 then salaire > 1000 else salaire > 2000 endif
salaire > (if age<40 then 1000 else 2000 endif)
megaplanet
9
StringString
name = nom.substring(1,1).toUpper().concat(
nom.substring(2,nom.size()).toLower())
Strings are not sequence of Sequence(char) (no char type)
Operations:Operations:
==
ss..sizesize()()
s1s1..concatconcat((s2s2))
s1s1..substringsubstring((i1i1,,i2i2))
ss..toUppertoUpper()()
ss..toLowertoLower()()
Values:Values:
''''
'a sentence''a sentence'
megaplanet
10
EnumerationEnumeration
ValuesValues
Day::TuesdayDay::Tuesday (previous notation:(previous notation: #Tuesday#Tuesday ))
OperatorsOperators
==,, <><>
No ordering relation
<<enumeration>>
Day
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
megaplanet
11
ExamplesExamples
spouse->notEmpty() implies spouse.sex = Sex::female
épouse.sexe < sexe
husband
0..1
Person
sex : Sex
spouse
0..1
No ordering relationNot always
defined
<<enumeration>>
Sex
male
female
megaplanet
12
Element vs. singletonElement vs. singleton
In almost all languagesIn almost all languages
one elementone element ee
from singleton containing this elementfrom singleton containing this element Set{e}Set{e}
self->size() = 1
Implicit conversion in OCLImplicit conversion in OCL element => singletonelement => singleton
when an collection operationwhen an collection operation
is applied to an elementis applied to an element
elemelem ->-> propprop Set{Set{elemelem}->}->propprop
≠
megaplanet
13
CollectionsCollections
General TypeGeneral Type CollectionCollection(( TT ))
Set(Set(TT ))
{unique}{unique} {nonunique}{nonunique}
{unordered}{unordered}
{ordered}{ordered} Sequence(Sequence(TT ))
Bag(Bag(TT ))
OrderedSet(OrderedSet(TT ))
megaplanet
14
Use of collections for role navigationUse of collections for role navigation
object . nomderoleobject . nomderole type:type:
X
1 or 0..1
X
*
X
{ordered} *
X
Set(X)
OrderedSet(X)
X
*{nonunique}
Bag(X)
X
{ordered, nonunique} *
Sequence(X)
megaplanet
15
Collection ExpressionsCollection Expressions
ExamplesExamples
SetSet {{ 'lundi''lundi',, 'mercredi''mercredi',, 'mardi''mardi' }}
BagBag {{ 'lundi''lundi',, 'lundi''lundi',, 'mardi''mardi',, 'lundi''lundi' }}
OrderedSetOrderedSet {{ 1010,, 2020,, 55 }}
SequenceSequence {{ 'lundi''lundi',, 'lundi''lundi',, 'mardi''mardi',, 'lundi''lundi' }}
To specify rangesTo specify ranges
SequenceSequence {{ 1..5, 2..41..5, 2..4 }}
Useful for 'loops' :
Sequence { 0 .. etagesnb-1 } -> forall( i | canStop(i) )
megaplanet
16
Operations on CollectionsOperations on Collections
Cardinality: coll -> size()
Emptyness: coll -> isEmpty()
Non emptyness: coll -> notEmpty()
Occurrence number: coll -> count(elem)
Membership: coll -> includes( elem )
Non membership: coll -> excludes( elem )
Inclusion: coll -> includesAll(coll)
Exclusion: coll -> excludesAll(coll)
Sum (of numbers): coll -> sum()
megaplanet
17
ExamplesExamples
Set { 3, 5, 2, 45, 5 }->size()
Sequence { 1, 2, 45, 9, 3, 9 } ->count(9)
Sequence { 1, 2, 45, 2, 3, 9 } ->includes(45)
Bag { 1, 9, 9, 1 } -> count(9)
c->asSet()->size() = c->size()
c->count(x) = 0
Bag { 1, 9, 0, 1, 2, 9, 1 } -> includesAll( Bag{ 9,1,9} )
megaplanet
18
Operations on SetsOperations on Sets
UnionUnion ens ->ens -> unionunion( ens )( ens )
IntersectionIntersection ens ->ens -> intersectionintersection( ens )( ens )
DifferenceDifference ens1 - ens2ens1 - ens2
Adding an elementAdding an element ens ->ens -> includingincluding(elem)(elem)
Removing an elementRemoving an element ens ->ens -> excludingexcluding(elem)(elem)
Sequence conversionSequence conversion ens ->ens -> asSequence()asSequence()
Bag conversionBag conversion ens ->ens -> asBag()asBag()
Conversion to ordered setConversion to ordered set ens ->ens -> asOrderedSet()asOrderedSet()
megaplanet
19
Filtering: select, reject and anyFiltering: select, reject and any
coll -> select( cond )
select elements satisfying the conditionselect elements satisfying the condition
coll -> reject( cond )
reject elementsreject elements
coll -> any( cond )
selectselect anyany element satisfying the conditionelement satisfying the condition
• non deterministnon determinist
• useful when there is only one elementuseful when there is only one element
• "undefined" if the collection is empty"undefined" if the collection is empty
megaplanet
20
ExamplesExamples
self.children ->select( age>10 and sex = Sex::Male)
self.children ->reject(e : Person | e.children->isEmpty())->notEmpty()
members->any(title='president')
children*
Member
sex : Sexe
age : integer
title : string
parents0..2Club members
*
megaplanet
21
Syntax AlternativesSyntax Alternatives
self.employees->select(age > 50)
self.employees->select( p | p.age>50 )
self.employees->select( p : Person | p.age>50)
Person
age : integer
Company
employees
*
megaplanet
22
forall, exists, oneforall, exists, one
coll ->coll -> forallforall( cond )( cond )
coll ->coll -> existsexists( cond )( cond )
coll ->coll -> oneone( cond )( cond )
self.enfants->forall(age<10)
self.enfants->exists(sexe=Sexe::Masculin)
self.enfants->one(age>=18)
children*
Person
sexe : Sex
age : integer
parents0..2
megaplanet
23
Syntax ComparisonSyntax Comparison
children->forall( p : Person | p.age<10)
∀ c ∈ children . c.age < 10
megaplanet
24
Quantifiers: more about syntaxQuantifiers: more about syntax
It's possible toIt's possible to
give a name to a variablegive a name to a variable
explicit its typeexplicit its type
use various variables at the same timeuse various variables at the same time
self.children->forall( age < self.age )
self.enfants->forall( e | e.age < self.age - 7)
self.children->forall( e : Personne | e.age < self.age - 7)
self.children->exists( e1,e2 | e1.age = e2.age )
self.children->exists( e1,e2 | e1.age = e2.age and e1<>e2 )
self.children->forall( e1,e2 : Personne |
e1 <> e2 implies e1.firstname <> e2.firstname)
children*
Person
age
firstname
megaplanet
25
UnicityUnicity
coll -> isUnique ( expr )
True if all elements return a different value for exprTrue if all elements return a different value for expr
self.children -> isUnique ( firstname )
instead ofinstead of
self.children->forall( p1,p2 : Person |
p1 <> p2 implies p1.firstname <> e2.firstname)
Useful to define the notion of "imported key" for instance
children*
Person
age
firstname
megaplanet
26
isUnique vs. {unique}isUnique vs. {unique}
self.children -> isUnique ( firstname )
children*
Person
age
firstname
{unique}
megaplanet
27
Image of an expression: collectImage of an expression: collect
coll ->coll -> collectcollect( expr )( expr )
"image" of a function (map, apply, ...)
expr evaluated for each element
result in:
a Bag if coll is a Set or a Bag
a Sequence if coll is a Sequence or a OrderedSet
self.enfants->collect(age) = Bag{10,5,10,7}
self.employés->collect(salaire/10)->sum()
children*
Person
age
employees
*
Company Employee
salary
megaplanet
28
Collect: Simplified Syntax!Collect: Simplified Syntax!
.. with a collectionwith a collection ↔↔ collectcollect
children*
Person
age
self.children.age
self.children->collect(age)
megaplanet
29
Collect Possible Duplicates→Collect Possible Duplicates→
The result is a Bag or Sequence because of possible duplicatesThe result is a Bag or Sequence because of possible duplicates
To get a setTo get a set
self.children.age->asSet()
. shortcut very usefull to navigate!. shortcut very usefull to navigate!
self.children.children.cars
children*
Person
age
Cars
cars
**

UML OCL : An Expression Language - Core -- 29

  • 1.
    megaplanet OCL : AnExpression LanguageOCL : An Expression Language Basic Types, Enumerated Types, Types ConstructorsBasic Types, Enumerated Types, Types Constructors Expressions, OperationsExpressions, Operations Operations on collectionsOperations on collections
  • 2.
    megaplanet 2 OCL = AnExpression LanguageOCL = An Expression Language No side effectNo side effect No explicit iterationNo explicit iteration Like a functional languageLike a functional language but no functions (in the standard)but no functions (in the standard) Can serve as aCan serve as a query languagequery language This first part, « OCL : An Expression language » is almost independent from UML
  • 3.
    megaplanet 3 TypesTypes Basic typesBasic types IntegerInteger RealReal BooleanBoolean StringString EnumeratedtypesEnumerated types MetatypesMetatypes OclTypeOclType OclAnyOclAny OclStateOclState OclExpressionOclExpression Types from UMLTypes from UML classesclasses associationsassociations …… Type constructorsType constructors TupleType( x : T, y : T … )TupleType( x : T, y : T … ) Set(T)Set(T) OrderedSet(T)OrderedSet(T) Sequence(T)Sequence(T) Bag(T)Bag(T) Collection(T)Collection(T)
  • 4.
    megaplanet 4 Syntax of ExpressionsSyntaxof Expressions (Simplified) <const> 12 'hello' <id> children Residence <expr> <op> <expr> age>18 self like in python, « this » in java <exprobj> . <prop> self.chairman.age <exprobj> . <objprop>(<expr>...) self.chairman.increaseSalary(10) <exprcoll> -> <collprop>(<expr>...) self.employees->collect(salary) <package>::<package> … :: <element> like in C++, « . » in python and java if <expr> then <expr> else <expr> endif if age>18 then 1200 else 50*age endif let <id> : <type> in <expr> .<expr> let e=x*x+y in (e-20)*1,5
  • 5.
    megaplanet 5 ExamplesExamples self.salary - 100 self.children->isEmpty() self.children->forall(age>20) self.getTaxes(1998)/ self.children->size() self.children->select( sex= Sex::male ) self.children->collect(salary)->sum() self.children.salary->sum() self.children->union(self.parents)->collect(age) children * Person sex:Sex salary:real age:integer parents 0..2 getTaxes() <<enumeration>> Sex male female
  • 6.
    megaplanet 6 To be Remembered!To be Remembered ! . to get access to properties of objects ->-> to get access to properties of collectionsto get access to properties of collections + some rules to mix collections and objects (see later) self.taxes(1998) / self.children -> size() because self is an object because self.children is a collection of objects
  • 7.
    megaplanet 7 Integer et RealIntegeret Real IntegerInteger values :values : 1, -5, 34, 243431, -5, 34, 24343, ..., ... operations :operations : +, -, *, div, mod, abs, max, min+, -, *, div, mod, abs, max, min RealReal values :values : 1.5, 1.341.5, 1.34, ..., ... operations :operations : +, -, *, /, floor, round, max, min+, -, *, /, floor, round, max, min Integer type « conforms » to the type Real
  • 8.
    megaplanet 8 BooleanBoolean BooleanBoolean values :values :truetrue,, falsefalse operations :operations : notnot,, andand,, oror,, xorxor,, impliesimplies,, if-then-else-endifif-then-else-endif partial evaluation :partial evaluation : true oror x always true, even when x is undefined false andand x always false, even when x is undefined (age<40 implies salaire>1000) and (age>=40 implies salaire>2000) if age<40 then salaire > 1000 else salaire > 2000 endif salaire > (if age<40 then 1000 else 2000 endif)
  • 9.
    megaplanet 9 StringString name = nom.substring(1,1).toUpper().concat( nom.substring(2,nom.size()).toLower()) Stringsare not sequence of Sequence(char) (no char type) Operations:Operations: == ss..sizesize()() s1s1..concatconcat((s2s2)) s1s1..substringsubstring((i1i1,,i2i2)) ss..toUppertoUpper()() ss..toLowertoLower()() Values:Values: '''' 'a sentence''a sentence'
  • 10.
    megaplanet 10 EnumerationEnumeration ValuesValues Day::TuesdayDay::Tuesday (previous notation:(previousnotation: #Tuesday#Tuesday )) OperatorsOperators ==,, <><> No ordering relation <<enumeration>> Day Monday Tuesday Wednesday Thursday Friday Saturday Sunday
  • 11.
    megaplanet 11 ExamplesExamples spouse->notEmpty() implies spouse.sex= Sex::female épouse.sexe < sexe husband 0..1 Person sex : Sex spouse 0..1 No ordering relationNot always defined <<enumeration>> Sex male female
  • 12.
    megaplanet 12 Element vs. singletonElementvs. singleton In almost all languagesIn almost all languages one elementone element ee from singleton containing this elementfrom singleton containing this element Set{e}Set{e} self->size() = 1 Implicit conversion in OCLImplicit conversion in OCL element => singletonelement => singleton when an collection operationwhen an collection operation is applied to an elementis applied to an element elemelem ->-> propprop Set{Set{elemelem}->}->propprop ≠
  • 13.
    megaplanet 13 CollectionsCollections General TypeGeneral TypeCollectionCollection(( TT )) Set(Set(TT )) {unique}{unique} {nonunique}{nonunique} {unordered}{unordered} {ordered}{ordered} Sequence(Sequence(TT )) Bag(Bag(TT )) OrderedSet(OrderedSet(TT ))
  • 14.
    megaplanet 14 Use of collectionsfor role navigationUse of collections for role navigation object . nomderoleobject . nomderole type:type: X 1 or 0..1 X * X {ordered} * X Set(X) OrderedSet(X) X *{nonunique} Bag(X) X {ordered, nonunique} * Sequence(X)
  • 15.
    megaplanet 15 Collection ExpressionsCollection Expressions ExamplesExamples SetSet{{ 'lundi''lundi',, 'mercredi''mercredi',, 'mardi''mardi' }} BagBag {{ 'lundi''lundi',, 'lundi''lundi',, 'mardi''mardi',, 'lundi''lundi' }} OrderedSetOrderedSet {{ 1010,, 2020,, 55 }} SequenceSequence {{ 'lundi''lundi',, 'lundi''lundi',, 'mardi''mardi',, 'lundi''lundi' }} To specify rangesTo specify ranges SequenceSequence {{ 1..5, 2..41..5, 2..4 }} Useful for 'loops' : Sequence { 0 .. etagesnb-1 } -> forall( i | canStop(i) )
  • 16.
    megaplanet 16 Operations on CollectionsOperationson Collections Cardinality: coll -> size() Emptyness: coll -> isEmpty() Non emptyness: coll -> notEmpty() Occurrence number: coll -> count(elem) Membership: coll -> includes( elem ) Non membership: coll -> excludes( elem ) Inclusion: coll -> includesAll(coll) Exclusion: coll -> excludesAll(coll) Sum (of numbers): coll -> sum()
  • 17.
    megaplanet 17 ExamplesExamples Set { 3,5, 2, 45, 5 }->size() Sequence { 1, 2, 45, 9, 3, 9 } ->count(9) Sequence { 1, 2, 45, 2, 3, 9 } ->includes(45) Bag { 1, 9, 9, 1 } -> count(9) c->asSet()->size() = c->size() c->count(x) = 0 Bag { 1, 9, 0, 1, 2, 9, 1 } -> includesAll( Bag{ 9,1,9} )
  • 18.
    megaplanet 18 Operations on SetsOperationson Sets UnionUnion ens ->ens -> unionunion( ens )( ens ) IntersectionIntersection ens ->ens -> intersectionintersection( ens )( ens ) DifferenceDifference ens1 - ens2ens1 - ens2 Adding an elementAdding an element ens ->ens -> includingincluding(elem)(elem) Removing an elementRemoving an element ens ->ens -> excludingexcluding(elem)(elem) Sequence conversionSequence conversion ens ->ens -> asSequence()asSequence() Bag conversionBag conversion ens ->ens -> asBag()asBag() Conversion to ordered setConversion to ordered set ens ->ens -> asOrderedSet()asOrderedSet()
  • 19.
    megaplanet 19 Filtering: select, rejectand anyFiltering: select, reject and any coll -> select( cond ) select elements satisfying the conditionselect elements satisfying the condition coll -> reject( cond ) reject elementsreject elements coll -> any( cond ) selectselect anyany element satisfying the conditionelement satisfying the condition • non deterministnon determinist • useful when there is only one elementuseful when there is only one element • "undefined" if the collection is empty"undefined" if the collection is empty
  • 20.
    megaplanet 20 ExamplesExamples self.children ->select( age>10and sex = Sex::Male) self.children ->reject(e : Person | e.children->isEmpty())->notEmpty() members->any(title='president') children* Member sex : Sexe age : integer title : string parents0..2Club members *
  • 21.
    megaplanet 21 Syntax AlternativesSyntax Alternatives self.employees->select(age> 50) self.employees->select( p | p.age>50 ) self.employees->select( p : Person | p.age>50) Person age : integer Company employees *
  • 22.
    megaplanet 22 forall, exists, oneforall,exists, one coll ->coll -> forallforall( cond )( cond ) coll ->coll -> existsexists( cond )( cond ) coll ->coll -> oneone( cond )( cond ) self.enfants->forall(age<10) self.enfants->exists(sexe=Sexe::Masculin) self.enfants->one(age>=18) children* Person sexe : Sex age : integer parents0..2
  • 23.
    megaplanet 23 Syntax ComparisonSyntax Comparison children->forall(p : Person | p.age<10) ∀ c ∈ children . c.age < 10
  • 24.
    megaplanet 24 Quantifiers: more aboutsyntaxQuantifiers: more about syntax It's possible toIt's possible to give a name to a variablegive a name to a variable explicit its typeexplicit its type use various variables at the same timeuse various variables at the same time self.children->forall( age < self.age ) self.enfants->forall( e | e.age < self.age - 7) self.children->forall( e : Personne | e.age < self.age - 7) self.children->exists( e1,e2 | e1.age = e2.age ) self.children->exists( e1,e2 | e1.age = e2.age and e1<>e2 ) self.children->forall( e1,e2 : Personne | e1 <> e2 implies e1.firstname <> e2.firstname) children* Person age firstname
  • 25.
    megaplanet 25 UnicityUnicity coll -> isUnique( expr ) True if all elements return a different value for exprTrue if all elements return a different value for expr self.children -> isUnique ( firstname ) instead ofinstead of self.children->forall( p1,p2 : Person | p1 <> p2 implies p1.firstname <> e2.firstname) Useful to define the notion of "imported key" for instance children* Person age firstname
  • 26.
    megaplanet 26 isUnique vs. {unique}isUniquevs. {unique} self.children -> isUnique ( firstname ) children* Person age firstname {unique}
  • 27.
    megaplanet 27 Image of anexpression: collectImage of an expression: collect coll ->coll -> collectcollect( expr )( expr ) "image" of a function (map, apply, ...) expr evaluated for each element result in: a Bag if coll is a Set or a Bag a Sequence if coll is a Sequence or a OrderedSet self.enfants->collect(age) = Bag{10,5,10,7} self.employés->collect(salaire/10)->sum() children* Person age employees * Company Employee salary
  • 28.
    megaplanet 28 Collect: Simplified Syntax!Collect:Simplified Syntax! .. with a collectionwith a collection ↔↔ collectcollect children* Person age self.children.age self.children->collect(age)
  • 29.
    megaplanet 29 Collect Possible Duplicates→CollectPossible Duplicates→ The result is a Bag or Sequence because of possible duplicatesThe result is a Bag or Sequence because of possible duplicates To get a setTo get a set self.children.age->asSet() . shortcut very usefull to navigate!. shortcut very usefull to navigate! self.children.children.cars children* Person age Cars cars **