67
1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science, Colorado State University. Other material from: (Source: http://www.cse.dmu.ac.uk/~aoc/teaching-notes/Contents/CSCI3007/CSCI3 007OCLtutorial.pdf )

1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

Embed Size (px)

Citation preview

Page 1: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

1

The Object Constraint Language: Expressing Constraints in the UML

(Most slides created by Robert B. France, ProfessorDepartment of Computer Science, Colorado State University. Other material from: (Source: http://www.cse.dmu.ac.uk/~aoc/teaching-notes/Contents/CSCI3007/CSCI3007OCLtutorial.pdf )

Page 2: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

2

What is OCL?

The Object Constraint Language (OCL) is a declarative language for describing rules that apply to UML models

OCL can be used to describe constraints

A constraint is a restriction on one or more values of a model or system.

A constraint is an expression that evaluates to true or false as a query language

Queries are expressions that evaluate to a value (true, false and other values)

Can be used to define new attributes and operations OCL expressions are always associated with a UML

model OCL expressions can be associated with any model element

in UML

Page 3: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

3

Specifying Constraints

Page 4: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

4

Different kinds of constraints Class invariant

a constraint that must always be met by all instances of the class

Precondition of an operation a constraint that must always be true BEFORE the

execution of the operation Postcondition of an operation

a constraint that must always be true AFTER the execution of the operation

Page 5: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

5

Specifying Constraints: Invariants

Page 6: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

6

Note: self can be omitted

context Flightinv capacity: maxNrPassengers <= 1000

Example: Expressing Invariants Flight capacity constraint: The maximum number of passengers

that can be on a flight must be less than or equal to 1,000.

context Flightinv capacity: self.maxNrPassengers <= 1000

Airport

Flight

*

*

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

arrivingFlights

departingFlights

1

1

Page 7: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

7

Constraint context and self

Every OCL expression is bound to a specific context. The context is often the element that the

constraint restricts The context may be denoted within the

expression using the keyword ‘self’. ‘self’ is implicit in all OCL expressions Similar to ‘this’ in C++

Page 8: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

8

Notation Constraints may be denoted within the

UML model or in a separate document. the expression:

context Flight inv durationLimit: self.duration < 4

is identical to:context Flight inv: duration < 4

Flight

duration: Integerinv: duration < 4

is identical to:

Page 9: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

9

Example model

Airport

Flight

Passenger

Airline

*

**

*

minAge: Integerage: IntegerneedsAssistance: Boolean

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

name: String

{ordered}

arrivingFlights

departingFlights

CEO

0..1

flights

passengers

book(f : Flight)

0..1

airline

airline

Time

difference(t:Time):Intervalbefore(t: Time): Booleanplus(d : Interval) : Time

$midnight: Timemonth : Stringday : Integeryear : Integerhour : Integerminute : Integer

Interval

equals(i:Interval):Boolean$Interval(d,h,m : Integer) : Interval

nrOfDays : IntegernrOfHours : IntegernrOfMinutes : Integer

11

1

1

Page 10: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

10

Airport

Flight

Passenger

Airline

*

**

*

minAge: Integerage: IntegerneedsAssistance: Boolean

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

name: String

{ordered}

arrivingFlights

departingFlights

CEO

0..1

flights

passengers

book(f : Flight)

0..1

airline

airline

Time

difference(t:Time):Intervalbefore(t: Time): Booleanplus(d : Interval) : Time

$midnight: Timemonth : Stringday : Integeryear : Integerhour : Integerminute : Integer

Interval

equals(i:Interval):Boolean$Interval(d,h,m : Integer) : Interval

nrOfDays : IntegernrOfHours : IntegernrOfMinutes : Integer

11

1

1

• Constraint: The difference between the depart and arrival time for a flight must be the same as its duration.

context Flightinv duration:

self.departTime.difference(self.arrivalTime).equals(self.duration)

Page 11: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

11

Elements of an OCL expression In an OCL expression these elements may

be used: basic types: String, Boolean, Integer, Real. classifiers from the UML model and their features

attributes, and class attributes associations from the UML model

Page 12: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

12

OCL types

Page 13: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

13

Precedence Rules

Page 14: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

14

Some OCL Reserved Words

AND ATTR ELSE ENDIF IF IMPLIES INV LET NOT OR POST PRE THEN XOR

Page 15: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

15

OCL Comments

Comments in OCL are written following two successive dashes “--”

-- this is a comment

Page 16: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

16

Airport

Flight

Passenger

Airline

*

**

*

minAge: Integerage: IntegerneedsAssistance: Boolean

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

name: String

{ordered}

arrivingFlights

departingFlights

CEO

0..1

flights

passengers

book(f : Flight)

0..1

airline

airline

Time

difference(t:Time):Intervalbefore(t: Time): Booleanplus(d : Interval) : Time

$midnight: Timemonth : Stringday : Integeryear : Integerhour : Integerminute : Integer

Interval

equals(i:Interval):Boolean$Interval(d,h,m : Integer) : Interval

nrOfDays : IntegernrOfHours : IntegernrOfMinutes : Integer

11

1

1

• context Airline inv: name.toLower = ‘usair’

• context Passenger inv: age >= ((9.6 - 3.5)* 3.1).floor implies mature = true

• NB: A B = ~A v B

Example: OCL basic types

Page 17: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

17

Associations and navigations

Every association in the model is a navigation path.

The context of the expression is the starting point.

Role names are used to identify the navigated association.

Page 18: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

18

Example: navigations

The name of the airline for a flight is Delta

context Flight

inv: airline.name = ‘Delta’

Airport

Flight

*

*

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

arrivingFlights

departingFlights

Airline

name: String

airline1 The origin of a flight must be different than its destination

context Flight

inv: origin <> destination

Page 19: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

19

Example: Invariant involving Enumerated Type

• The type of a flight must be the same as the type of the airplane.

{context Flightinv ftype = Ftype::cargo implies Airplane.atype = Ftype::cargoinv ftype = Ftype::passenger implies Airplane.atype = Ftype:: passenger}

1*Flight Airplane

ftype : Ftype atype : Ftypeflights

<<enumeration>>Ftype

cargopassenger

Page 20: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

20

Association classes Persons working with IBM have the job type “trainer”

otherwise their job type is “programmer”.context Person inv:if employer.name = ‘IBM’ then

Job.type = JobType::trainerelse Job.type = JobType::programmerendif

Person Company

Job

* 1employee employer

type : JobType

name : String

JobType

trainerprogrammer

Page 21: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

21

Specifying Constraints: Operation Specifications

Page 22: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

22

Syntax for specifying operationscontext NameOfClass::operationName():returnTypepre : -- some expressionbody : -- some expressionpost : some expression

Page 23: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

23

Pre- and PostCondition Example

A class named Account has an attribute balance and an operation overdraft() that returns true if the balance is less than 0 and false otherwise.

context Account::overdraft():Booleanpre : -- nonepost : result = (balance < 0)

Page 24: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

24

More complex operation specifications

The operation birthdayOccurs() adds 1 to the customer age.

context Customer::birthdayOccurs()pre : -- nonepost : age = age@pre + 1

What does this describe?

context Account::safeWithdraw(amt:Integer)pre : balance > amtpost : balance = balance@pre - amt

Page 25: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

25

Specifying Queries

Page 26: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

26

Example model

Airport

Flight

Passenger

Airline

*

**

*

$minAge: Integerage: IntegerneedsAssistance: Boolean

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

name: String

{ordered}

arrivingFlights

departingFlights

CEO

0..1

flights

passengers

book(f : Flight)

0..1

airline

airline

Time

difference(t:Time):Intervalbefore(t: Time): Booleanplus(d : Interval) : Time

$midnight: Timemonth : Stringday : Integeryear : Integerhour : Integerminute : Integer

Interval

equals(i:Interval):Boolean$Interval(d,h,m : Integer) : Interval

nrOfDays : IntegernrOfHours : IntegernrOfMinutes : Integer

11

1

1

Page 27: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

27

Derived Attribute & Initial Value Example

Defining derived attributes

context Flight::arrivalTime:Timederive:departTime.plus(duration)

Defining initial attribute value

context Flight::maxNrPassengers:Integerinit: 100

Defining initial association end value

context Flight::passengers:Set(Passenger)init: Set{}

Page 28: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

28

Query operation examplesReturn all the departing flights from a given airport

context Airport::departures():Set(Flight)body: result=departingFlights

Return all the airports served by an airline

context Airline::served():Set(Airport)body: result=flights.destination->asSet()

Airline

name: StringAirport

Flight

*

* *

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

arrivingFlights

departingFlights

flights

airline1

1

1

1

Page 29: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

29

More Advanced OCL Expressions

Page 30: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

30

Significance of collections in OCL Most navigations return collections rather

than single elements

10..*Flight Airplane

type : enum of cargo, passenger

type : enum of cargo, passenger

flights

Page 31: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

31

Subtypes of Collection

1. Set: each element occurs only once (Non-ordered, unique)

2. OrderedSet: a set with ordered elements.

3. Bag: elements may be present more than once(non-ordered, non-unique)

4. Sequence: a bag with ordered elements (ordered, non-unique)

Page 32: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

32

Subtypes of CollectionAirline

name: StringAirport

Flight

*

* *

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

arrivingFlights

departingFlights

flights

airline1

1

1

1

Passenger*

$minAge: Integerage: IntegerneedsAssistance: Boolean

{ordered}passengers

book(f : Flight)

Set: arrivingFlights - from the context Airport Non-ordered, unique

Bag: arrivingFlights.duration - from the context Airport Non-ordered, non-unique

Sequence: passengers - from the context Flight Ordered, non-unique

Page 33: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

33

Collection operations

OCL has a great number of predefined operations on the collection types.

Syntax: collection->operation

Use of the “->” (arrow) operator instead of the“.” (dot) operator

Page 34: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

34

The collect operation

Syntax:collection->collect(elem : T | expr)collection->collect(elem | expr)collection->collect(expr)

The collect operation results in the collection of the values resulting from evaluating expr for all elements in the collection

Shorthand often trips people up. Be Careful!

Page 35: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

35

Example: collect operation

context Airport inv:

self.arrivingFlights -> collect(airLine) ->notEmpty

airp1

airp2

f1

f2

f3

f4

f5

airline1

airline2

airline3

departing flights arriving flights

All arriving flights must be associated with an airline

Page 36: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

36

The select operation

Syntax:collection->select(elem : T | expression)

collection->select(elem | expression)

collection->select(expression)

The select operation results in the subset of all elements for which expression is true

Page 37: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

37

Example: select operation

context Airport inv:

self.departingFlights->select(duration<4)->notEmpty

departing flights

arriving flights

airp1

airp2

airline1

airline2

airline3

f5duration = 2

f1duration = 2

f4duration = 5

f2duration = 5

f3duration = 3

There must be at least one departing flight whose duration is less than 4

Page 38: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

38

The forAll operation

Syntax: collection->forAll(elem : T | expr) collection->forAll(elem | expr) collection->forAll(expr)

The forAll operation results in true if expr is true for all elements of the collection

Page 39: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

39

Example: forAll operation

context Airport inv:

self.departingFlights->forAll(departTime.hour>6)

departing flights arriving flights

airp1

airp2

airline1

airline2

airline3

f5depart = 8

f1depart = 7

f4depart = 9

f2depart = 5

f3depart = 8

All departing flights must leave after 6

Page 40: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

40

The exists operation

Syntax:collection->exists(elem : T | expr)collection->exists(elem | expr)collection->exists(expr)

The exists operation results in true if there is at least one element in the collection for which the expression expr is true.

Page 41: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

41

Example: exists operationcontext Airport inv:

self.departingFlights->exists(departTime.hour<6)

departing flights arriving flights

airp1

airp2

airline1

airline2

airline3

f5depart = 8

f1depart = 7

f4depart = 9

f2depart = 5

f3depart = 8

Page 42: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

42

Other collection operations

isEmpty: true if collection has no elements notEmpty: true if collection has at least one element size: number of elements in collection count(elem): number of occurences of elem in

collection includes(elem): true if elem is in collection excludes(elem): true if elem is not in collection includesAll(coll): true if all elements of coll are in

collection

Page 43: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

43

Examples

A vehicle owner must be at least 18 years old.:context Vehicle inv: self.owner. age >= 18

Page 44: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

44

A car owner must be at least 18 years old.:context Car inv: self.owner. age >= 18

Examples

Page 45: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

45

Nobody has more than 3 vehicles:context Person inv: self.fleet->size <= 3

Examples

Page 46: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

46

All vehicles of a person are black:context Person inv: fleet->forAll(v | v.colour = #black)

Examples

Page 47: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

47

Nobody has more than 3 red vehicles:context Person inv: fleet->select(v | v.colour = #red)->size <= 3

Examples

Page 48: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

48

context Personinv: age<18 implies self.fleet->forAll(v | not v.oclIsKindOf(Car))

A person younger than 18 owns no cars..

Examples

Page 49: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

49

There is a red car in somebody’s fleet:context Person inv: fleet->select(v | v.colour = #red)->notEmpty

context Car inv: Car.allInstances()->exists(c | c.colour=#red)

Examples

Page 50: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

50

Examples: pre-post conditions

If setAge(. . . ) is called with a non-negative argument then the argument becomes the new value of the attribute age.

context Person::setAge(newAge:int) pre: newAge >= 0 post: age = newAge

Page 51: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

51

Examples: pre-post conditions

Calling birthday() increments the age of a person by 1.

context Person::birthday() post: age = age@pre + 1

Page 52: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

52

Examples: pre-post conditions

Calling getName() delivers the value of the attribute name.

context Person::getName() post: result = name

Page 53: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

53

Local variables The let construct defines variables local to

one constraint:Let var : Type = <expression1> in <expression2>

Example:context Airport inv:Let supportedAirlines : Set (Airline) =

self.arrivingFlights -> collect(airLine) in (supportedAirlines ->notEmpty) and (supportedAirlines ->size < 500)

Page 54: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

54

Iterate

The iterate operation for collections is the most generic and complex building block.

collection->iterate(elem : Type;

answer : Type = <value> |

<expression-with-elem-and-answer>)

Page 55: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

55

Iterate example

Example iterate:context Airline inv:flights->select(maxNrPassengers > 150)->notEmpty

Is identical to:context Airline inv:flights->iterate (f : Flight;

answer : Set(Flight) = Set{ } |if f.maxNrPassengers > 150 then

answer->including(f)else

answer endif )->notEmpty

Page 56: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

56

Inheritance of constraints

Guiding principle Liskov’s Substitution Principle (LSP): “Whenever an instance of a class is expected,

one can always substitute an instance of any of its subclasses.”

Page 57: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

57

Inheritance of constraints Consequences of LSP for invariants:

An invariant is always inherited by each subclass. Subclasses may strengthen the invariant.

Consequences of LSP for preconditions and postconditions: A precondition may be weakened (contravariance)

A method in a subclass can weaken the precondition of a method in the superclass. That means the subclass method can accept a wider range of values. So data that is valid in the subclass may be invalid in the superclass.

A postcondition may be strengthened (covariance) A subclass’s method can strengthen the postcondition (but it cannot

weaken it): a subclass‘s method can return a subset of the values returned by the method it overrides.

Page 58: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

Weakening Preconditions

abstract class Payment { /** * @pre amt >= 0 */ public void setPaymentAmount(int amt) {…} }

58

class CreditCardPayment extends Payment { /** * @pre amt >= 25 */ public void setPaymentAmount(int amt) {…} }

// @pre true class CashPayment extends Payment { … }

Payment

setPaymentAmount(amt:int)

CreditCardPayment

setPaymentAmount(amt:int)

CashPayment

setPaymentAmount(amt:int)

@pre: amt >= 0

@pre: amt >= 0

@pre: true

Page 59: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

Why does it not make sense to strengthen the precondition?

59

Example from: http://www.ugrad.cs.ubc.ca/~cs211/notes/L07-InheritanceGoodBad-4up.pdf

Payment

setPaymentAmount(amt:int)

CreditCardPayment

setPaymentAmount(amt:int)

CashPayment

setPaymentAmount(amt:int)

• Client should be able to do:

Payment p;// substitute CashPayment for Payment

p = new CashPayment();

p.setPaymentAmount( 5 );// substitute CreditCardPayment for Payment

p = new CreditCardPayment();

p.setPaymentAmount( 5 ); // oops!

@pre: amt >= 0

@pre: amt >= 0

@pre: true

Page 60: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

Why does it not make sense to weaken the postcondition? • Suppose the client writes code based on the postcondition of the

superclass. • That client code could break if we substitute a superclass object

with an instance of one of its subclasses if the subclass' method has a weaker postcondition. • client writes code assuming that a method returns a value that is positive • subclass overrides method to return *any* value (so postcondition is weakened) • client code is going to break if a negative value is returned.

60

Page 61: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

61

Exercise: The Stack Data Structure isFull() – returns true if stack has maximum number of elements isEmpty() – returns true if stack has no elements top() – returns element on top of stack previous(Element elm) – returns the element inserted on the

stack immediately before elm. push(Element elm) – add elm to top of stack pop() – removes and returns element on top of stack

Assuming isFull, previous and top are already specified, specify pre and post conditions for the other operations.

Page 62: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

62

Summary and OCL Tips

OCL invariants allow you to model more precisely remain implementation independent

OCL pre- and postconditions allow you to specify contracts (design by contract) specify interfaces of components more precisely

OCL usage tips keep constraints simple always combine natural language with OCL use a tool to check your OCL

Page 63: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

Further Resources for OCL

The Object Constraint Language ISBN 0-201-37940-6

Page 64: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

64

ConclusionFinally!

!

Page 65: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

The End

CSC550, Devon M. Simmonds, Computer Science Department, University of North Carolina Wilmington

???????????????

…CSC550 …

Q u e s t i o n s ?

Page 66: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

66

Why OCL?

Required age of car owners? Requirement that a person may own at most one red car

- because UML is not enough!

Page 67: 1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,

67

Constraints vs. Queries

Examples of constraints: Duration of a flight is the same as the difference between the arrival and

departure times The maximum number of passengers on a flight must be less than

1,001 The origin of a flight must be different than its destination

Examples of queries: Return all the departing flights from a given airport Return all the flights departing from a given airport with a departure time

after 4p.m. Derive the arrival time by adding the duration of the flight to the

departure time.

Airport

Flight

*

*

departTime: Time/arrivalTime: Timeduration : IntervalmaxNrPassengers: Integer

origin

desti-nation

name: String

arrivingFlights

departingFlights

1

1