Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

OCL

No description
by

Alexandre MAGNE

on 8 November 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of OCL

Preconditions et postconditions (pre, post)
Precondition
: constraint that must be checked before the call of an operation.
Post

condition
: constrain that must be checked after the call of the function
II- Types of constraints
Example :
pre
: <logical_expression>
post
: <logical_expression>
context
Account::debit(sum : Real)
pre
: sum > 0
post
: account = account@pre - sum
I- Introduction
II- Type of Constraints
III- Building Models with OCL
IV- Implementing OCL
V- Basics OCL Elements
VI- User-defined Types
What is OCL ?
CUNAULT Romain
KHATTARI Ilias
MAGNE Alexandre
NGUYEN Nam Son

UML Presentation : OCL
Contents

OCL = Object Constraint Language
Formal language
Language of constraints != programing
Add information to a basic
UML diagram
Why OCL ?
Easy to use
Easy to understand
I- Introduction
Based Example
Context
Constraint : always associated with model element
II- Types of constraints
Example without OCL
2 ways to specifiy the context :
Bank
Person
Writing constraint between braces ({}) in a note The element pointed by the note is the context of constraint
Account
-balance : int
+credit(int)
+debit(int)
Example :
+getBalance():int
Using keyword context in an other document
owner
customer
*
*
*
1
*
1
If context is the class "Account" :
context
Account
If context is the function gatBalance() in class "Account" :
context
Account::getBalance()
Bank
Person
Account
-balance : int
+credit(int)
+debit(int)
+getBalance():int
owner
customer
*
*
*
1
*
1
Invariants
Have to be respected at all time
II- Types of constraints
Example :
Syntax :
inv
: <logical_expression>
context:
account
inv
balance>0
context:
account::debit (amount : int)
pre:
balance>0
post:
balance=balance@pre-amount
The account balance must always be positive.

context
Account
inv
: Balance > 0
Bank
Customer
Account
-balance : int
+credit(int)
+debit(int)
+getBalance():int
owner
customer
*
*
*
1
*
1
UML class diagram
UML
OCL
context
Account::getBalance() : Real
post
:
result
= balance
context
Account::getBalance() : Real
Result of a method (body)
Initialization (init) and changing attributes (derive)
Init
constraint applies only when creating an instance. It can fluctuate.
Derive
constraint imposes perpetual constraint
II- Types of constraints
Example :
init : <requête>
derive : <requête>
context
Personne::employer : Set(Society)
init
: Set{}
Question ?
result
attribute
: value returned by the operation
<attribute_name>
@pre
means the value of the attribute <attribute_name> before calling the operation.
Information
In these examples, we have not described how the operation is performed, but only state of constraints before and after execution.
For method "Debit" of Account class
The result of calling the "getBalance" operation must be equal to the "balance" attribute.
context
Personne::age : Integer
derive
: birthday - Date::current()
III- Building Models with OCL
What is a Model ?
Describes a system using a well-defined language

Class diagrams and the statecharts show items that describe the same system
The Context Definition
The link between an entity in a UML diagram and an OCL expression

Specifies the model entity for which the OCL expression is defined

Contextual Type of an Expression
The contectual type is the type of the context, or of its container


Example

OCL expressions and their context
III- Building Models with OCL
Use UML Diagrams as a Base
Most important diagram in the model is the class diagram

Use of OCL strongly relies on the types defined in a UML class diagram.


Identify where the need for explicitly stating extra information lies.

III- Building Models with OCL
Modeling Styles
OCL expressions also be used to express the same information in a different manner

Various styles of modeling



Definitions of Attributes or Operations
Attributes or operations may be defined in the class diagram

Example
Two attributes, wellUsedCards and loyalToCompanies, and one operation, cardsForProgram, are defined :
context Customer
def: wellUsedCards : Set( CustomerCard )
= cards->select( transactions.points->sum() > 10,000 )
def: loyalToCompanies : Bag( ProgramPartner )
= programs.partners
def: cardsForProgram(p: LoyaltyProgram) : Set(Cards)
= p.Membership.card
The expression following the equal sign in an attribute definition indicates how the value of the attribute must be calculated. It is a derivation rule
The Subset Constraint
This constraint means that the set of links for one association is a subset of the set of links for the other association.
III- Building Models with OCL
Tips & Hints
Split and Constraints
Choose Context Wisely
Avoid Complex Navigation Expressions
The following expression specifies that a Membership does not have a loyaltyAccount if you cannot earn points in the program :
context Membership
inv noEarnings: programs.partners.deliveredServices->
forAll(pointsEarned = 0) implies account->isEmpty()
Instead of navigating such a long way, we might want to split this constraint. We define a new attribute isSaving for LoyaltyProgram :
context LoyaltyProgram
def: isSaving : Boolean =
partners.deliveredServices->forAll(pointsEarned = 0)
The invariant for Membership can use the new attribute, rather than navigate through the model. The new invariant looks much simpler:
context Membership
inv noEarnings: programs.isSaving implies account->isEmpty()
It is important to attach an invariant to the right type

There are no strict rules that can be applied in all circumstances, but the following guidelines will help :
If the invariant restricts the value of an attribute of one class, the class containing the attribute is a clear candidate
If the invariant restricts the value of attributes of more than one class, the classes containing any of the attributes are candidates
If a class can be appointed the responsibility for maintaining the constraint, that class should be the context.
In general, it is much better to split a complicated constraint into several separate constraints

The advantages of spliting invariants are considerable :
Each invariant becomes less complex and therefore easier to read and write
When you are determining whether an invariant is appropriate, the discussion can focus precisely on the invariant concerned, instead of on the complex invariant as a whole
The same arguments hold for pre- and postconditions. When a precondition is broken during execution, the problem can be pinpointed much more effectively when you are using small, separate constraints
I- Introduction
I- Introduction
None side effect
Bank
Person
Account
-balance : int
+credit(int)
+debit(int)
+getBalance():int
owner
customer
*
*
*
1
*
1
UML with OCL
{balance>0}
First proposal
In a bank :
- accounts
- customers

Problem : if I have 1000 constraints
Second proposal
With UML :
All constraints are not written
=> modeling error
A person can :
- have 0 or * bank
- have 0 or * accounts
1 account belongs to:
- one bank
- one person
without OCL
Implementation without error :
Here we have problem :
Constraints :
- one account must belong to one person and one bank
- one customer must have one account
- one owner must have one bank

Other constraints
- balance>0
- amount to debit > 0
body
: <request>
V- Basics OCL Elements
Example Boolean Type
Example if..then..else..endif
if <boolean OCL expression>
then <OCL expression>
else <OCL expression>
endif

not true
age() > 21 and age() < 65
age() <= 12 xor cards->size() > 3
title = 'Mr.' or title = 'Ms.'
name = 'Foobar'
if standard = 'UML'
then 'using UML standard'
else 'watch out: non UML features'
endif

The result value of an if-then-else operation is the result of either the OCL expression in the then clause or the OCL expression in the else clause, depending on the result of the boolean expression in the if clause.

Uncommon to most programming languages: implies operation

V- Basics OCL Elements
Example Integer and Real Types
For the Integer and Real types, the usual operations apply: addition, subtraction, multiplication, and division
2654 * 4.3 + 101 = 11513.2

(3.2).floor() / 3 = 1

1.175 * (-8.9).abs() - 10 = 0.4575

12 > 22.7 = false

12.max(33) = 33

33.max(12) = 33

13.mod(2) = 1

13.div(2) = 6

33.7.min(12) = 12.0

-24.abs() = 24

(-2.4).floor() = -3

V- Basics OCL Elements
Example String Types
The operations available on Strings are toUpper, toLower, size, substring, and concat

'Anneke'.size() = 6
('Anneke' = 'Jos') = false
'Anneke '.concat('and Jos') = 'Anneke and Jos'
'Anneke'.toUpper() = 'ANNEKE'
'Anneke'.toLower() = 'anneke'
'Anneke and Jos'.substring(12, 14) = 'Jos'

VI- User-defined Types

Features of User-Defined Types
Attributes and Operations
• Attributes
• Operations
• Class attributes
• Class operations
• Association ends that are derived from associations and aggregations

Class Operations and Attributes
Attributes of user-defined types may be used in expressions by writing a dot followed by the attribute name.

HOWEVER
, one fundamental restriction:
OCL is a side-effect-free language, operations that change the state of any object are not allowed.

The name of the operation followed by two parentheses, which enclose the optional arguments of the operation.

Necessary to distinguish between
-
Attributes

-
Operations

Class operations and class attributes may also be used in OCL expressions.
The syntax for referencing —> the class name followed by:
two colons,
the attribute or operation name (and parameters).


For example:

context CustomerCard
inv: goodThru.isAfter( Date::now )

VI- User-defined Types

Associations and Aggregations
Association Classes
Qualified Associations
Classes attached to an association
Always navigate to the instances of the classes at all ends of the association
Results in one single value
Can navigate from association class to another association class


Can be used in OCL expressions in the same way that normal associations are used
Synthax —> object.navigation[qualifierValue, …]
If there are multiple qualifiers, their values are separated by commas
Identical to navigation of normal association

context CustomerCard
inv: self.owner.dateOfBirth.isBefore( Date::now )

context CustomerCard
inv: self.owner.programs->size() > 0

context Membership
inv: programs.levels->includes( currentLevel )

context LoyaltyProgram
inv: levels->includesAll( Membership.currentLevel )


context LoyaltyProgram
inv: self.levels[1].name = 'basic'

context LoyaltyProgram
inv: self.levels->exists(name = 'basic')

VI- User-defined Types

Enumeration Types
context Customer
inv: gender = Gender::male implies title = 'Mr.'

Often used as a type for attributes
The values defined in the enumeration can be used as values within an OCL expression
The only operators available on enumeration values
the equality and inequality operators
similar to a postcondition:
post
: result = balance
Define the result of an operation
body
: balance

IV- Implementing OCL
Implementing Process
Define the implementation of the UML model elements
Define the implementation of the OCL standard library
Define the implementation of the OCL expressions
Place the code fragments implementing the OCL expressions correctly in the code for the model elements

IV- Implementing OCL
Implementing UML Model Elements
Maintaining the connection with the implementation of the OCL expressions

Implementing the OCL Standard Library
OCL Basic Types
Predefined basic OCL types should be mapped to basic types in the target language
Mapping of basic types from OCL to Java
OCL Collection Types
Java provides a large number of different collection types

OCL collections have a large number of predefined operations

Mapping of collection types from OCL to Java

Implementing OCL Expressions
IV- Implementing OCL
Evaluation order is not (and does not need to be) defined in OCL
It is perfectly legal to write a constraint and have part of that constraint undefined

Getting Attribute and AssociationEnd Values
Any attribute reference in OCL needs to be mapped to the corresponding get operation

For instance, the OCL expression :

self.attribute
Is transformed into the following Java code:

this.getAttribute();
Let Expressions
A let expression can be implemented by defining a local variable

In the next example, the operation selectPopularPartners selects program partners that have generated numerous large transactions after the given date :

context LoyaltyProgram::selectPopularPartners( d: Date )
: Set(ProgramPartner)
post: let popularTrans : Set(Transaction) =
result.deliveredServices.transactions->asSet()
in
popularTrans->forAll( date.isAfter(d) ) and
popularTrans->select( amount > 500.00 )->size() > 20000

Treating Instances as Collections
The simplest way to translate such an expression into Java is to introduce a temporary collection that holds the instance as the only element

The following OCL expression from the context of Membership uses a LoyaltyAccount object as collection:
account->size()
The parts of the OCL expression that can be recognized are printed in boldface:
account->size()
Set coll = new HashSet();
if( account != null ) coll.add( account );
return coll.size();
Exercice
Exercice 1 :
In a class room :

- number of students must be <= 25
- you can add a student
- you can remove a student
DIAGRAM CLASS and OCL :
Exercice 2 :
Baloon :
An air ballon is composed by a
balloon
and a
weights
.
Balloon has a
temperature
, that can be recovered and a
volume
. The weight has obviously a
mass
. The baloon also. We can
let go
weight and
raise
the baloon

DIAGRAM CLASS and OCL :

HINT :
brown => attribute
Blue => functions
Bold => Class
Full transcript