Introduction to OCL Fernando Brito e Abreu (fba@di.fct.unl.pt) - - PDF document

introduction to ocl
SMART_READER_LITE
LIVE PREVIEW

Introduction to OCL Fernando Brito e Abreu (fba@di.fct.unl.pt) - - PDF document

Introduction to OCL Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/QUASAR) Abstract Why formalization? Formalization in OO OCL types and


slide-1
SLIDE 1

1

Introduction to OCL

Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt)

QUASAR Research Group (http://ctp.di.fct.unl.pt/QUASAR)

Abstract

Why formalization? Formalization in OO OCL types and operators Design by contract Collection operations Examples

slide-2
SLIDE 2

2

Why is formalization required?

 Graphical elements of the diagrammatic

specifications are very powerful and obvious

 easy to understand how they fit together ;)

 Modeling details, such as uniqueness and

referential restraints, limitations and other constraints are expressed ambiguously

 often they cannot be conveyed graphically  examples: Christian marriage, who‟s the boss, ...

Who‟s the boss of the boss?

boss 0..1

Employee

name : string

slide-3
SLIDE 3

3

Christian marriage On rails …

front_car 1 waggons 0..1 * loco 1 Train Waggon Locomotive Car

train_id : integer waggon_id : integer number_places : integer horse_power : integer

slide-4
SLIDE 4

4

The quest for formalization ...

 Accuracy and unambiguity in specification is the

aim of the branch of computer science known as “formal methods”

 Several attempts have been made to combine

them with object-oriented modeling …

Formal methods in OO (1/4)

 Extending

and adapting an existing formal languagewith object-oriented constructs

 Ex: Z++, Object-Z, VDM++

 This approach is not in line with industrial practice

trends to use the simple, but powerful, graphical notations in OOAD.

 Most practitioners

are not at ease in using traditionalformalspecification languages...

slide-5
SLIDE 5

5

Z, Z++ and Object Z

 Z is a specification language developed by the

Programming Research Group at Oxford University

"Understanding Z", J.M.Spivey, Cambridge U Press, 1988

 Z is used for describing and modeling computing systems

It is based on axiomatic set theory and first order predicate logic Z is written using many non-ASCII symbols

 Z++ is an object-oriented extension of Z

"Z++, an Object-Oriented Extension to Z", Lano, Z User Workshop,

Oxford 1990, Springer Workshops in Computing, 1991, pp.151-172

 Object Z is another object-oriented extension of Z

developed at University of Queensland, Australia

"Object Orientation in Z", S. Stepney et al eds, Springer 1992

An Object-Z extract …

slide-6
SLIDE 6

6

Formal methods in OO (2/4)

 Complementing

diagrammatic notations with some existing formallanguage constructs

 Ex: Syntropy (subset of Z combined with OMT), ROOA

(A. Moreira), Metamorphosis (J. Araújo)

 Compromise

solution, joining the benefits

  • f

graphicalmodelingand formallanguages

 Drawback1: conceptual gap between formalisms  Drawback2: same as in previous approach

A bit of Syntropy

slide-7
SLIDE 7

7

Formal methods in OO (3/4)

 Use of a constraint language to express design by

contractmodeling issues(B.Meyer)

 Ex: BON (Business Object Notation) object-oriented

method (Waldén 95).

 Has a full-fledged textual assertion mechanism, allowing to

specify system structure and semantics (constraints, invariants, properties of expected results)  Bridges

the semantic gap but failed widespread acceptance (too tied to Eiffel language world)

 Acceptance often comes from standardization ...

BON:

Elevator example

slide-8
SLIDE 8

8

Formal methods in OO (4/4)

 The last and more promising road is OCL  Allows

to specify invariants, preconditions, postconditions, guard conditions, and other types

  • f constraints (restrictions)

 Therefore

supports design by contract as proposedby Bertrand Meyer

 Is a part of the UML standard published by the

OMG (let‟s have a look at it ...)

 Used

in the standard itself to clarify the semanticsof the graphicalnotations (why?)

Unclear semantics of the UML metamodel (example)

Can the grandpa inherit from the grandson?

slide-9
SLIDE 9

9

Object Constraint Language

 It is a formal, yet simple notation, to be used jointly

with UML diagrams

 Its syntax has some similarities to those of some

OO programming languages

 It is underpinned by mathematical set theory and

logic, like in formal languages

 However it was designed for usability and is easily

grasped by those familiar with OO modeling concepts (particularly UML ones)

Object Constraint Language

 OCL brings the best of the previous

approaches:

simplicity and powerfulness of graphical

notations

preciseness and non-ambiguity granted by

formality, in a usable and conceptually integrated fashion

Moreover, since it is a part of UML, it has

become a de jure standard

 also de facto because there is an increasing number

  • f UML tools supporting OCL
slide-10
SLIDE 10

10

OCL syntax

 OCL is strongly type checked  Style convention is Camel Case starting with:

Lower case letter: objects, attributes, operations Upper case letter: classes

 Dot notation is used for:

Attribute access Operation access Association end access (navigation in diagram)

OCL examples

Class:

 Person, Date

Objects:

 boy, girl

Attributes:

 boy.name  girl.birthday

Operations:

 boy.marries(girl), girl.age()

Note: parameterless operations can be written with or without parenthesis

Class attribute:

 Person.allInstances

Navigation through an association:

 boy.spouse.name

slide-11
SLIDE 11

11

Navigation example

Consider the object:

bill: Customer

 Attribute access

bill.name

 Operation access

bill.age()

 Navigation through associations

bill.cards bill.cards.color

Class invariants

 Invariants are constraints that represent

conditions that must be met by all class instances, atall times.

 Their context is, therefore, a class  Context can be represented differently:

Example:

  • - every customer must be at least 18 years old

OMG standard USE tool

Customer inv CustomerAge: age() >= 18 context Customer inv CustomerAge: age() >= 18

slide-12
SLIDE 12

12

Design by contract

PRE-CONDITION POST-CONDITION CLIENT Obligation Right SUPPLIER Right Obligation

Operation assertions

 Pre-conditions are constraints that must be true

before an operation is executed

 In the design by contract paradigm, they represent the

rights of the object that offers the service or, if you want, the client responsibilities.

 Post-conditions are constraints that must be true

when the operation ends its execution

 They represent the obligations to be fulfilled by the object

that offers the service, or, if you want, the client rights.

slide-13
SLIDE 13

13

Operation assertions: example

 The context of both pre and post-conditions is,

therefore, an operation: Math::factorial(value:Integer):Integer pre:value >= 0 post:result = if value = 0 then 1 else value * factorial(value-1) endif

This is a scope indicator

OCL types

OclAny Enumeration Collection Real Integer Sequence Bag Set String Boolean

OclAny is the superclass of all classes in OCL (even user defined ones)

slide-14
SLIDE 14

14

OclAny

 OclAny is the supertype of all model types  Features on OclAny are available on each

  • bject in all OCL expressions

 To avoid name conflicts between features in

the model and features inherited from OclAny, all names on the OclAny features start with „ocl‟

Features of OclAny

(note: object is the instance of OclAny)

  • bject = (object2 : OclAny) : Boolean
  • - True if object is the same object as object2.
  • bject <> (object2 : OclAny) : Boolean
  • - True if object is a different object as object2.
  • bject.oclType : OclType
  • - The type of an object
slide-15
SLIDE 15

15

Features of OclAny

(note: object is the instance of OclAny)

  • bject.oclIsTypeOf(t : OclType) : boolean
  • - true if t is the type of self

post: result = (object.oclType = t)

  • bject.oclIsKindOf(t : OclType) : boolean
  • - true if t is either the type of object or one of its

supertypes post: result = object.oclType.allSuperTypes

  • >includes(t) or (object.oclType = t)

Features of OclAny: example

mario: Student (Student is subclass of Person) mario.oclType

  • - results in Student

mario.oclIsTypeOf( Student )-- is true mario.oclIsTypeOf( Person ) -- is false mario.oclIsKindOf( OclAny) -- is true mario.oclIsKindOf( Person ) -- is true

slide-16
SLIDE 16

16

OclType

 All types defined in an UML model, or pre-

defined within OCL, have a type

 That type is an instance of the OclType

metaclass

Access to OclType allows the modeler to

access the model meta-level (reflexivity)

Reflexivity: features of OclType

(note: type is the instance of OclType)

type.name : String The name of type type.attributes : Set(String) The set of names of the attributes of type, as they are defined in the model type.associationEnds : Set(String) The set of names of the navigable associationEnds of type, as they are defined in the model type.operations : Set(String) The set of names of the operations of type, as they are defined in the model type.supertypes : Set(OclType) The set of all direct supertypes of type. post: type.allSupertypes->includesAll(result) type.allSupertypes : Set(OclType) The transitive closure of the set of all supertypes of type type.allInstances : Set(type) The set of all instances of type and all its subtypes Example: Customer.allInstances Transaction.allInstances

slide-17
SLIDE 17

17

Features of OclAny

(note: object is the instance of OclAny)

  • bject.oclAsType(type : OclType) : type

Results in object, but of known type type. Results in Undefined if the actual type of object is not type or one of its subtypes pre : object.oclIsKindOf(type) post: result = object post: result.oclIsKindOf(type)

Standard operators

Type Operations Boolean =, not, and, or, xor, implies, if-then-else Real =, +, -, *, /, abs, floor, max, min, <, >, <=, >= Integer =, +, -, *, /, abs, div, mod, max, min, <, >, <=, >= String =, size, toLower, toUpper, concat, substring

Notes

  • The “=“ operator is a relational operator (comparison), not an assignment one!
  • The “if-then-else” is a conditional evaluation operator, not a control flow structure!
slide-18
SLIDE 18

18

OCL Collection types

Duplicates Order Set No No Bag Yes No Sequence Yes Yes

Collection operations

Collection is an abstract class

Collection

size() : Integer includes(object : OclAny) : Boolean count(object : OclAny) : Integer includesAll(c2 : Collection(T)) : Boolean isEmpty() : Boolean notEmpty() : Boolean sum() : Real exists(expr : OclExpression) : Boolean forAll(expr : OclExpression) : Boolean iterate(expr : OclExpression) : OclType

Sequence Bag Set Collection

slide-19
SLIDE 19

19

Set operations

A Set is a non ordered collection without duplicates

Set

union(set2 : Set(T)) : Set (T) union(bag1 : Bag(T)) : Bag (T) =(set2 : Set(T)) : Boolean intersection(set2 : Set(T)) : Set (T) intersection(bag1 : Bag(T)) : Bag (T)

  • (set2 : Set(T)) : Set (T)

including(object : T) : Set (T) excluding(object : T) : Set (T) symmetricDifference(set2 : Set(T)) : Set (T) select(expr : OclExpression) : Set (T) reject(expr : OclExpression) : Set (T) collect(expr : OclExpression) : Set (expr.evaluationType()) count(object : T) : Integer asSequence() : Sequence (T) asBag() : Bag (T)

Bag operations

A Bag is a unordered collection that may hold duplicate elements

Bag

=(bag2 : Bag(T)) : Boolean union(bag2 : Bag(T)) : Bag (T) union(set1 : Set(T)) : Bag (T) intersection(bag2 : Bag(T)) : Bag (T) intersection(set1 : Set(T)) : Set (T) including(object : T) : Bag (T) excluding(object : T) : Bag (T) select(expr : OclExpression) : Bag (T) reject(expr : OclExpression) : Bag (T) collect(expr : OclExpression) : Bag (expr.evaluationType[)) count(object : T) : Integer asSequence() : Sequence (T) asSet() : Set (T)

slide-20
SLIDE 20

20

Sequence operations

A Sequence is a ordered collection that may hold duplicate elements

Sequence

count(object : T) : Integer =(sequence2 : Sequence(T)) : Boolean union(sequence2 : Sequence(T)) : Sequence (T) append(object : T) : Sequence (T) prepend(object : T) : Sequence (T) subSequence(lower : Integer, upper : Integer) : Sequence (T) at(at : Integer) : T first() : T last() : T including(object : T) : Sequence (T) excluding(object : T) : Sequence (T) select(expr : OclExpression) : Sequence (T) reject(expr : OclExpression) : Sequence (T) collect(expr : OclExpression) : Sequence (expr.evaluationType[)) iterate(expr : OclExpression) : OclType asBag() : Bag (T) asSet() : Set (T)

More assertion examples

Collection inv IsAbstractClass: Collection.allInstances->select(oclType = Collection)- >isEmpty() Sequence::prepend(object:T):Sequence(T) post:result->size() = self@pre->size()+1 post:result->at(1)= object

“@pre” is a timing tag (state at preconditions evaluation) “->” is used to apply an

  • peration to a collection
slide-21
SLIDE 21

21

Expressing uniqueness constraints

  • - Customer identifiers should

always be unique

Customer (H1) Customer.allInstances->forAll(c1, c2: Customer | c1 <> c2 implies c1.client_id <> c2.client_id) (H2) Customer.allInstances->count(client_id = self.client_id)=1 (H3) Customer.allInstances->isUnique(client_id) Which is the least efficient implementation?

Customer

client_id : Integer name : String title : String isMale : Boolean dateOfBirth : Date age()

Navigation and collections

 OCL expressions can be built by navigating

in the class diagram

 By definition, the result of navigating

through just one association is a Set

 The result of navigating through more than

  • ne association where at least one has

multiplicity many is a Bag.

Exception: if the association is adorned with

the {ordered}tag, we get a Sequence.

slide-22
SLIDE 22

22

Navigation example

Customer not self.related_with->includes(self)

  • - what does this mean?

+related_with 0..* Customer

client_id : Integer name : String title : String isMale : Boolean dateOfBirth : Date age()

“Royal & Loyal” case study

 Loyalty program management system  Customers must become members to get an

accountand then have cards

 Customers make earning and burning

transactions

 Transactions are associated with a given card  Program partners offer services of a given level  Adapted example from [Warmer & Kleppe 1999]

slide-23
SLIDE 23

23

Burning Earning Membership LoyaltyAccount

0..1

1

0..1

1 ProgramPartner ServiceLevel 1 0..*

+actualLevel

1 0..* Transaction

0..*

1

+transactions 0..*

1 Service

0..*

1

+deliveredServices 0..*

1 0..* 1

+availableServices

0..* 1 0..* 1 +transactions 0..* 1 LoyaltyProgram

1..*

1..*

+partners 1..*

1..*

1..*

1

1..* {ordered}

1 CustomerCard 1 1 +card 1 1 0..* 1 +transactions 0..*

+card

1 Customer 0..* 0..* +program 0..* 0..* 1

0..* +owner

1

+cards 0..*

0..* 0..*

+related_with

Navigation and naming rules

Rule 0 - Class names start with an uppercase

letter and role names with a lowercase letter

Rule 1 - While navigating from a class to

another, if the role of the destination class is defined then use it. Otherwise apply rule 2

Rule 2 - While navigating from a class to

another, if the role of the destination class is not defined, then use the name of the destination class starting with a lowercase letter

slide-24
SLIDE 24

24

Navigating and naming rules

Problem: a card issued for a membership is in the possession of the customer who is mentioned in the membership

Membership

card.owner = customer

Navigating and naming rules

Problem: construct a function “program()” that returns the loyalty program corresponding to the transaction Transaction::Program():LoyaltyProgram = (H1) card.membership.program (H2) service.serviceLevel.loyaltyProgram (H3) ? (H4) ? (H5) ?

slide-25
SLIDE 25

25

Enumerations

 Enumeration values are prefixed with “ #”

Ex 1: a CustomerCard coloris silver or gold CustomerCard

color = #silver or color = #gold

Ex 2: the card color relative to a given membership must match the corresponding service level Membership

actualLevel.name = 'Silver' implies card.color = #silver and card.color = #silver implies actualLevel.name = 'Silver' and actualLevel.name = 'Gold' implies card.color = #gold and card.color = #gold implies actualLevel.Name = 'Gold'

Operations over collections

 The partners of a given program cannot burn

more than 10000 points (as a whole)

LoyaltyProgram

partners.deliveredServices.transactions-> select (oclType = Burning)->collect(points)->sum < 10000

  • - same as above but using the shorthand for collect

partners.deliveredServices.transactions.points->sum < 10000

  • - is there something wrong?
slide-26
SLIDE 26

26

Operations over collections

 The partners of a given program cannot burn

more than 10000 points (individually)

LoyaltyProgram

partners->forAll(p: Partner | p.deliveredServices.transactions-> select (oclType = Burning)->collect(points)->sum < 10000) partners->forAll(deliveredServices.transactions-> select (oclType = Burning)->collect(points)->sum < 10000)

Notation may be simplified ...

 Example: there is one service level whose

name is 'basic‟

LoyaltyProgram

  • - inv BasicService:

self.serviceLevel->exists( s: ServiceLevel | s.name = 'basic' )

  • - inv BasicService2:

serviceLevel->exists( s | s.name = 'basic' )

  • - inv BasicService3:

serviceLevel->exists( name = 'basic' )

slide-27
SLIDE 27

27

Expressing operation semantics

Date::isBefore(t:Date): Boolean = if self.year = t.year then if self.month = t.month then self.day < t.day else self.month < t.month endif else self.year < t.year endif

Date

day : Integer month : Integer year : Integer now : Date isBefore(t : Date) : Boolean isAfter(t : Date) : Boolean isEqual(t : Date) : Boolean yearsSince(t : Date) : Integer today() : Date yearsTo(t : Date) : Integer

Operation semantics example

 Customer.age() ?  Customer.age():Integer =

(H1) dateOfBirth.today().yearsSince( dateOfBirth ) (H2) dateOfBirth.yearsTo( dateOfBirth.today() )

Date

day : Integer month : Integer year : Integer now : Date isBefore(t : Date) : Boolean isAfter(t : Date) : Boolean isEqual(t : Date) : Boolean yearsSince(t : Date) : Integer today() : Date yearsTo(t : Date) : Integer

Customer

client_id : Integer name : String title : String isMale : Boolean dateOfBirth : Date age()

slide-28
SLIDE 28

28

Invariant example

 The initial date of the card

validity must be previous to the cancellation date

CustomerCard inv CardValidity: (H1) validFrom.isBefore(goodThru) (H2) goodThru.isAfter(validFrom)

Date

day : Integer month : Integer year : Integer now : Date isBefore(t : Date) : Boolean isAfter(t : Date) : Boolean isEqual(t : Date) : Boolean yearsSince(t : Date) : Integer today() : Date yearsTo(t : Date) : Integer

Invariant example

 The name printed in the card is a concatenation of

the owner title followed by the owner name CustomerCard printedName = owner.title.concat(owner.name) Customer cards->forAll(printedName=self.title.concat(self.name))

slide-29
SLIDE 29

29

Invariant example

 The number of valid cards for every

customer must be equal to the number of programs the customer participates in CustomerCards program->size = cards->select(valid)->size

Invariant example

 A customer cannot hold more than one valid

card for every program in which he participates

Customer program->forAll(membership.card-> select (valid and (owner=self))->size <=1)

slide-30
SLIDE 30

30

Invariant example

Senior customers (above 65 years old) earn bonuses

in earning transactions. This means that the points they get in each transaction is the one specified in the corresponding service plus an increase of 15%.

Earning let seniorBonus: Real = 0.15, oldAge: Integer = 65 in card.owner.age() > oldAge implies points = (service.pointsEarned * (1+seniorBonus)).floor Note: multiple variable definition is included in the OCL2 standard, but in the USE tool only one variable is supported

Operation semantics example

 Write the predicate Alarm that allows detecting

that a given balance (alarm level) between burned points and earned points was exceeded, for a named LoyaltyProgram

LoyaltyProgram::Alarm(level: Real): Boolean= Burning.allInstances->select(program() = self) -> collect(points)->sum > (Earning.allInstances->select(program() = self) -> collect(points)->sum) * level

slide-31
SLIDE 31

31

Now that you are feeling confident :)

 Example: Valid cards are "gold" for holders that

have had in the past some card (expired before the issue of the current one) within the same program, for which they have had transactions of at least 150000 points or if they have always had done more than 5000 points worth of transactions for all expired cards, no matter which program. If cards are not gold then they are "silver”!!!

This is almost correct. Why?

CustomerCard

color = if membership.program.customer.cards ->select(owner = self.owner) -> exists(goodThru.isBefore(self.validFrom) and transactions.points->sum >= 15000) or owner.cards -> select (goodThru.isBefore(self.validFrom)) -> forAll (transactions.points -> sum > 5000) then #gold else #silver endif

slide-32
SLIDE 32

32

Re-typing or Casting

 In some circumstances it is desirable to use a

property of an object that is defined on a subtype

  • f the current known type of the object

 Since the property is not defined on the current known

type, this results in a type conformance error

 When it is certain that the actual type of the object

is the subtype, the object can be re-typed using the operation oclAsType(OclType)

 This operation results in the same object, but the known

type is the argument OclType

 An object can only be re-typed to one of its subtypes  If the actual type of the object is not equal to the type to

which it is re-typed, the expression is undefined

Re-typing or Casting

 Example:

? a: Animal -- evaluates to type Animal ? a.oclAsType(Fish) --- evaluates to type Fish

slide-33
SLIDE 33

33

Adding OCL to UML models

Graphic Editors

System X Diagrams System Z Diagrams System Y Diagrams

Modeling Tools

Tool Repository

OCL Expressions Evaluator

UML Model Workload (Model Objects) OCL Expressions (Model Constraints) Expression Results

Workload Generator

UML Model

USE: Model file (*.use)

 The model is stored in textual format  Model includes the definition of

Classes (with their attributes and operations) Association classes (idem, plus association info) Associations, aggregations and/or compositions Invariants (at the class level) Pre and post conditions (at the operation level)

slide-34
SLIDE 34

34

Example (Company)

model Company class Employee attributes name: String salary: Integer

  • perations

getName(): String end … … class Department attributes budget: Integer end class Project attributes budget: Integer end …

Example (continued)

association WorksIn between Employee[ 1..* ] role employee Department[ 1 ] role place end association WorksOn between Employee[ 1..* ] role colaborators Project[ 1..* ] role project end association Controls between Department[ 1] role place Project[ 1..* ] role project end

slide-35
SLIDE 35

35

Example (continued)

  • - OCL constraints

constraints context Department

  • - the number of employees working in a department must
  • - be greater or equal to the number of projects
  • - controlled by the department

inv MoreEmployeesThanProjects: self.employee->size >= self.project->size

Example (continued)

… context Employee

  • - employees get a higher salary when they work on
  • - more projects

inv MoreProjectsHigherSalary: Employee.allInstances->forAll(e1, e2 | e1.project->size > e2.project->size implies e1.salary > e2.salary)

slide-36
SLIDE 36

36

Example (continued)

… context Project

  • - the budget of a project must not exceed the
  • - budget of the controlling department

inv BudgetWithinDepartmentBudget: self.budget <= self.department.budget

  • - employees working on a project must also work in the
  • - controlling department

inv EmployeesInControllingDepartment: self.department.employee->includesAll(self.employee)

USE tool (model loaded)

slide-37
SLIDE 37

37

USE tool (no objects) Model instantiation

 Models can be instantiated:

interactively, or through a batch facility (command language)

slide-38
SLIDE 38

38

USE: Model commands

 open [-q] FILE

Reads information from FILE

 The FILE extension here is “use” (the model file)  “-q” is for quiet reading  info model

Info about loaded model

 info class NAME

Info about class

USE: Model commands

 read FILE

Reads commands from FILE

 readq FILE

Reads commands quietly from FILE

 The FILE extension here is “cmd”  info state

Info about current system state

 The system state is given by its objects and links

 info vars

Prints information about global variables

 reset

Reset system to empty state

 This means keeping the model but deleting the objects

and links

slide-39
SLIDE 39

39

USE: Information commands

Help Print available commands help CMD Info about the given command info prog Print internal program infos q, quit, exit Exit USE

USE: Query commands

 ! CMD

 Executes state manipulation command

 : EXPR

Compiles EXPR and shows its static type

 use> : Set{2004,2005,2006,2007}->select(e | e > 2005)  -> Set(Integer)

 ? EXPR

Compiles and evaluates EXPR

 use> ? Set{2004,2005,2006,2007}->select(e | e > 2005)  -> Set{2006,2007} : Set(Integer)

 ?? EXPR Compiles and evaluates EXPR (verbose)

 use> ? Set{2004,2005,2006,2007}->select(e | e > 2005)  -- see the verbosity for yourself 

slide-40
SLIDE 40

40

USE: State manipulation commands

 !create <id-list> : <class> [between (<id-list>)]

 Creates objects (class instances)  If <class> is an association class, then the link ends

must be given after 'between'

 !destroy <id-list>

 Destroys objects; id-list may be a collection

 !set <obj-id>.<attr-id> := <expr>

 Set attribute value of object

 !let <id> [ : <type> ] = <expr>

 allows to bind new variables

Example (continued)

!create john: Employee !create frank: Employee !create cs: Department !set john.name = “Johnny Walker” !destroy Employee.allInstances

  • - removes all Employee objects
slide-41
SLIDE 41

41

USE tool (with objects)

USE: Association commands

 !insert (<id-list>) into <assoc>

 Creates a link (association instance); the id-list must

conform to the association definition

 !delete (<id-list>) from <assoc>

 Deletes a link among identified objects from the named

association

slide-42
SLIDE 42

42

Example (continued)

!insert (john,cs) into WorksIn !insert (frank,cs) into WorksIn !create research : Project !set research.name := 'Research„ !set research.budget := 12000 !create teaching : Project !set teaching.name := 'Validating UML„ !set teaching.budget := 3000 !insert (cs,research) into Controls !insert (cs,teaching) into Controls !insert (frank,research) into WorksOn !insert (frank,teaching) into WorksOn !insert (john,research) into WorksOn

The USE tool

slide-43
SLIDE 43

43

USE: Checking integrity constraints

 check [-v] [-d] [ -a | inv-list ]

  • v

Verbose output of subexpression results for failing invariants

  • d

Show which instances cause and invariant to fail.

  • a

Check all invariants (including the loaded ones from the generator)

inv-list Check only given invariants (space separated)

Signature of an invariant is <context>::<invName>

USE: Checking integrity constraints

context CustomerCard inv CardValidity1: validFrom.isBefore(goodThru) inv CardValidity2: goodThru.isAfter(validFrom)

 use> check CustomerCard::CardValidity1

slide-44
SLIDE 44

44

Checking constraints (browser)

Implementation of OCL in USE

OCL syntax

Implicit flattening is only done when used with the shorthand notation for collect. For instance: company.branches.employees

results in a Bag(Employee)

company.branches->collect(c | c.employees)

results in a Bag(Set(Employee))

This result can be flattened into a Bag(Employee) by explicit flattening the collection with the `flatten' operation added in USE: company.branches->collect(c | c.employees)->flatten

slide-45
SLIDE 45

45

Implementation of OCL in USE

OCL syntax

Type checking requires that empty collections must be specified as:

  • clEmpty(<collection-type>)

For example:

  • clEmpty(Set(Integer))

instead of

  • Set{}

Implementation of OCL in USE

OCL semantics

Some OCL operations are non-deterministic, e.g.,

  • Set(T)->asSequence

The result of these operations are implementation

  • dependent. The equation:
  • s1->asSequence = s1->asSequence

will therefore be wrong in general.

slide-46
SLIDE 46

46

Implementation of OCL in USE

OCL extensions/variations

Collection types can be nested to any level, e.g.,

  • Bag(Set(Sequence(Person)))

All types include an undefined value. For example, the expression 1/0 results in the value Undefined of type Integer Checking for an undefined value can be done with the new

  • perations "isDefined()" and "isUndefined()“

These are defined for all types (that is, in OclAny) e.g.: (1/0).isUndefined() results in "true"

An undefined value may be explicitly specified with the new

  • peration "oclUndefined(T)" where T may be any type

USE: Generator commands

 gen unload [invnames]

 Unloads added class invariants

 gen loaded

Prints loaded class invariants

 gen flags [invnames] [+d|-d] [+n|-n]

 Switch invariant evaluation flags

 gen start [options] FILE PROCNAME([params])

 Search valid system state

 gen result Prints results of last generator search  gen result inv Prints statistics of last generator search  gen result accept Accept result of last generator search

slide-47
SLIDE 47

47

USE: Model animation and validation

 A model can be animated to validate the

specification against non-formal requirements

 System states (snapshots of a running system)

can be created and manipulated during an animation

 For each snapshot the OCL constraints are

automatically checked

 Information about a system state is given by graphical

views

 OCL expressions can be entered and evaluated to

query detailed information about a system state

USE: Animation commands

!openter <obj-expr> <name> ([<expr-list>]) Enters object operation !opexit [<result-expr>] Exits least recently entered operation info opstack Print currently active operations stepon Activates single-step mode

slide-48
SLIDE 48

48

OCL Tools

Feature IBM Parser Dresden Toolkit TU Munich Tool ModelRun (… Rose) Bremen USE Syntactical analysis

    

Type checking

   

Logical consistency checking Dynamic invariant validation

  

Dynamic pre / post condition validation

Test automation

Code verification and synthesis

OCL Tools

More on OCL tools can be found at: http://www.klasse.nl/ocl/ocl-tools.html

slide-49
SLIDE 49

49

Some bits of history ...

Version Date Submitters / Supporters

1.1 (36 p.) Sep 1997 Rational, Microsoft, Hewlett

  • Packard, Oracle, Sterling

Software, MCI Systemhouse, Unisys, ICON Computing, IntelliCorp, i

  • Logix, IBM, ObjecTime,

Platinum Technology, Ptech, Taskon, Reich Technolog ies, Softeam 1.2 … … 1.3 June 1999 … 1.4 … … 2.0 (214 p.) Jan 2003 Submitters: Boldsoft, Rational, IONA, Adaptive Ltd. Supporters : Klasse Objecten, Borland, Kings College, University of Bremen, Dresden University of Technology, Kabira Technologies, IBM, Telelogic, University of Kent, Project Technology, University of York, Compuware, Syntropy Ltd., Oracle, Softeam

What is new in OCL 2.0?

 Its grammar has been extended, but keeps its

retro-compatibility with OCL 1.4

 The OCL grammar (its concepts and semantics)

are described using a MOF 2.0-compliant metamodel

 This metamodel defines and acts as an abstract

syntax for the language

 Alternative concrete syntaxes (e.g. Java-like syntax

  • r visual constraint diagrams) can be supported
slide-50
SLIDE 50

50

OCL features evolution

 OCL 1.* is side-effect free (only selectors allowed)

 Selectors are query operations which return a value but do not

change the object state (their label isQuery = true)

 OCL 2.* allows expressing messages sent by

components, classes or other constructs that may have behavior (using the OclMessage concept)

 This allows the specification of behavioral constraints

 UML 1.4 predefined types and operations are defined as

the OCL 2.0 Standard Library.