Advance Software Engineering OCL: By: Dr. Salwa Osama
Advance Software Engineering OCL: By: Dr. Salwa Osama
OCL
By:
Dr. Salwa Osama
Any model
• Any model is splits into three types:
1. Predictive model: Analyze the past for the future
2. Descriptive model: creating the relationship in the data - grouping
3. Perspective model: decision based on all the elements -prescribing
/**
*
* @param Screen
*/
public void setScreen(String Screen) {
// TODO - implement ATM.setScreen
throw new UnsupportedOperationException();
}
}
Using Visual Paradigm
Example2: Property analysis and verification
• The following code controls the change of colors in tree lights.
switch(color){
case "blue":{color="red"; break;}
case "green":{color="yellow"; break;}
case "yellow":{color="blue"; break;}
case "red":{color="yellow"; break;}
}
Example2: Property analysis and verification
• The following code controls the change of colors in tree lights.
• The code in previous slide can be trivially from this model.
• For larger state machine models we probably need automated
reachability analysis
Modeling Languages
• Large number of off-the-shelf modeling languages
• Each language focuses on specific class of domains, problems and
systems
• UML (object oriented systems)
• Simulink (control systems)
• Archimate (enterprise architecture)
• BPMN (business modeling)
• ER (rational databases)
Domain-Specific Languages
• Often models are useful for the problem at hand, but
existing language lack appropriate abstraction
• Example; Organizing conferences
Conference Organization
• A conference runs over a number of days
• On every day, there are several talks organized in (potentially parallel)
tracks.
• There are breaks between tracks (e.g. for lunch, coffee etc.)
• Each talk can be delivered by one or more speakers
• Each talk ha a pre-defined duration
Artefacts Involved
Conference Model
UML 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.
OCL
• OCL is The Object Constraint Language in UML
• First developed in 1995 as IBEL by IBM’s Insurance division for
business modelling.
• OCL was used to define UML 1.2 itself.
• Companies 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
Textbook: “The Objection Constraint Language: Precise Modeling with UML”, by Jos Warmer and Anneke Kleppe
Advantages 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
Where 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
Example: A Mortgage System
19
OCL specification of the constraints:
20
More Constraints Examples
• All players must be over 18. Player
context Player invariant:
self.age >=18 age: Integer
• The number of guests in each room doesn’t exceed the number of beds in
the room.
Room room guest Guest
*
numberOfBeds: Integer
21
Constraints (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 <context name>
• A dashed note line connecting to the context figure in the UML models
• A constraint might have a name following the keyword
invariant.
22
Example 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).
23
LoyaltyProgram Customer
1..*
0..* 0..* name: String
1..* partners enroll(c:Customer) program title:String
ProgramPartner isMale: Boolean
1 dateOfBirth: Date
numberOfCustomers: Integer 0..* Membership
age(): Integer
partner 1 {ordered} 1..* 1 actualLevel 1 1 owner
0..1
ServiceLevel 0..* card
LoyaltyAccount card
name: String CustomerCard
deliveredServices 0..* points: Integer 1
1 level valid: Boolean
Service earn(i: Integer)
0..* validForm: Date
burn(i: Integer)
condition: Boolean goodThru: Date
availableServices isEmpty(): Boolean
pointsEarned: Integer color: enum{silver,
1 account
pointsBurned: Integer transactions 0..* gold}
description: String printedName: String
Transaction
generatedBy 1 points: Integer card
0..* 1
transactions
date:Date 0..*
Date program(): LoyaltyProgram transactions
$now: Date
isBefore(t:Date): Boolean
isAfter(t:Date): Boolean
=(t:Date): Boolean Burning Earning 24
Using OCL in Class Diagrams
LoyaltyAccount class invariant
points: Integer { points >= 0 }
earn(i: Integer)
<<postcondition>>
points = points@pre + i
<<postcondition>>
points = points@pre - i
<<postcondition>>
result = (points=0) postcondition for burn operation
25
Invariants on Attributes
◼ Invariants on attributes:
context Customer
invariant agerestriction: age >= 18
context CustomerCard
invariant correctDates: validFrom.isBefore(goodThru)
26
Invariants 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 >= 18
27
Invariants 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.
28
Invariants 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 ->, followed by the operation name.
31
OCL Type Hierarchy
Models
OCL- Context
OCL - Types
OCL – Collections
Models
Context
Pre, post- Conditions
Navigation
context CustomerCard
invariant printedName:
printedName =
owner.title.concat(‘ ‘).concat(owner.name)
OCL - Types
OCL ANY
Valued logic for OCL
• Collection is a predefined OCL type
• Operations are defined for
collections
• They never change the original
• Three different collections:
OCL Collections • Set (no duplicates)
• Bag (duplicates allowed)
• Sequence (ordered Bag)
• OrderSet (ordered Set)
• 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->operation
OCL Collections
36
Examples
• Select (select or ->select): Returns a context Library
collection containing the elements that inv: books->select(b | b.available =
satisfy a specified condition. false)->isEmpty()
This OCL expression checks if there are no unavailable books in the library
Examples
Collect (collect or ->collect): Applies a context ShoppingCart
transformation to each element of a inv: items->collect(i | i.product.price *
collection, producing a new collection. i.quantity)->sum() <= user.balance
This OCL expression calculates the total cost of items in the shopping
cart and checks if it's within the user's balance.
Examples
Reject (reject or ->reject): Returns a context TaskList
collection containing the elements that inv: tasks->reject(t | t.completed)-
do not satisfy a specified condition. >isEmpty()
This OCL expression checks if there are no incomplete tasks in the task
list.
Examples
ForAll Checks if a condition is true for all context ShoppingCart
elements in a collection. inv: items->forAll(i | i.quantity > 0)
This OCL expression ensures that the quantity of each item in the
shopping cart is greater than zero.
Examples
Exists checks if there is at least one context Library
element in a collection that satisfies a inv: books->exists(b | b.popularity > 100)
specified condition.
This OCL expression checks if there is at least one book in the library
with a popularity score greater than 100.
Changing the context
Customer StoreCard
name:String 1..* printName:String
title: String owner cards points: Integer
golduser: Boolean
earn(p:Integer)
age( ):Integer
context StoreCard
invariant: printName = owner.title.concat(owner.name)
context Customer Note switch of context!
cards → forAll (
printName = owner.title.concat(owner.name) )
38
Example
33
Example
33
Example
33
Example UML diagram
submits Assessment
1..* weight: Integer
Exam Coursework
hours: Integer date: String
39
Constraints
a) Modules can be taken iff they have more than seven
students registered
b) The assessments for a module must total 100%
c) Students must register for 120 credits each year
d) Students must take at least 90 credits of CS modules each
year
e) All modules must have at least one assessment worth
over 50%
f) Students can only have assessments for modules which
they are taking
40
Constraint (a)
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() > 7
41
Constraint (b)
b) The assessments for a module must total 100%
context Module
invariant:
set_work.weight→sum( ) = 100
42
Constraint (c)
c) Students must register for 120 credits each year
context Student
invariant: takes.credit→sum( ) = 120
43
Constraint (d)
d) Students must take at least 90 credits of CS modules
each year
context Student
invariant:
takes →
select(code.substring(1,2) = ‘CS’).credit→sum( ) >= 90
44
Constraint (e)
e) All modules must have at least one assessment
worth over 50%
context Module
invariant: set_work→exists(weight > 50)
45
Constraint (f)
f) Students can only have assessments for modules which they are
taking
context Student
invariant: takes→includesAll(submits.for_module)
46
Pre, Post Conditions
context Company::hire(p : Person)
pre hirePre1: p.isDefined()
pre hirePre2: employee->excludes(p)
post hirePost: employee->includes(p)