You are on page 1of 47

Object Constraint Language

Design by Contract and Queries Dan Massey Y&L Consulting

OCL Topics
Object Constraint Language (OCL)
OCL for Design by Contract OCL for Queries

Another OCL Example

OCL Topics
Object Constraint Language (OCL)
OCL for Design by Contract OCL for Queries

Another OCL Example

Object Constraint Language


OCL 2.0 Product of the Object Management Group (OMG) Add-on to the Unified Modeling Language (UML) 2.0 specification UML combined with OCL forms a solid base for Model Driven Architecture (MDA)

Model Driven Architecture


Work with Platform Independent Model (PIM) Transform PIM into Platform Specific Model (PSM)
Transform PSM into implementation

Model Constraints
Originally viewed as a way to constrain or to restrict values in a model In addition OCL supports: Query expressions Derived values Conditions Business rules

Reasons to use OCL


Express concepts that are not supported by UML diagrams Make models more precise
Support transformation tools and code generation (MDA)

Approach
Were going to explore OCL by example to give you ideas as to where it might apply in your work.
At the end Ill point you toward sources of more complete information.

OCL Topics
Object Constraint Language (OCL)
OCL for Design by Contract OCL for Queries

Another OCL Example

Design by Contract
Why do we use contracts? We know the rules. We know what happens if we break them.
Design by Contract does the same for software. Provide a formal specification of behavior.

More Design by Contract


winningBid():Bid is a signature, not a specification. Its like giving someone a phone without providing the format for a correct phone number.
Are there any conditions that must be met for a call to winningBid() to succeed?

And Design by Contract


Specify preconditions, postconditions, and invariants. Defensive programming? Well cover each of these in turn.
Bertrand Meyer is the father of DbC http://www2.inf.ethz.ch/personal/meyer/

Auction Domain

A partial auction domain to get us started. Includes Auction, Bid, and Money. We have the structure, but what are the rules?

OCL Expression Context

Every OCL expression takes place in a context: context Auction context Auction::winningBid():Bid

Preconditions

Preconditions are the conditions that must be true prior to successfully invoking the method in question. Often preconditions that fail result in exceptions.

Example Preconditions
context Auction::placeBid(bidder:Id, bid:Money) pre : not bidder.oclIsUndefined() pre : not bid.oclIsUndefined() pre : bid.currency = self.bids->first().amount.currency pre : bid > self.currentBid().money

Simple Preconditions
context Auction::placeBid(bidder:Id, bid:Money) pre : not bidder.oclIsUndefined() pre : not bid.oclIsUndefined()

This operation requires a bidder identifier and a bid.

Implementing Preconditions
public void placeBid(Id bidder, Money bid) { if (bidder == null) { throw new NullPointerException( bidder may not be null); }

More Involved Preconditions


context Auction::placeBid(bidder:Id, bid:Money) pre : bid.currency = self.bids->first().amount.currency pre : bid > self.currentBid().money
The bid must be in the same currency as the starting bid. The bid must be higher than the current high bid.

Implementing Preconditions
if (bid.getAmount().getCurrency() != ((Bid) bids.first()).getAmount() .getCurrency()) { throw new IllegalArgumentException( currencies must match); }

Assertion Temptation
// Dont do this. Anyone who runs your app // can turn off assertions. assert bidder != null : bidder may not be null; assert bid.getAmount().getCurrency() == ((Bid) bids.first()).getAmount() .getCurrency() : currencies must match;

OCL Comments
context Auction::placeBid(bidder:Id, bid:Money) -- currencies must match pre : bid.currency = self.bids->first().amount.currency pre alwaysTrue : 1 = 1
-- and /**/ are valid comment forms in OCL

More Preconditions

Preconditions are not limited to checking parameters. They can specify any condition that must be true prior to executing the operation. What are some other possible preconditions?

More Preconditions
context Auction::winningBid():Bid -- auction must end to have a winner pre : TimeStamp::now() >= self.expires()
context Bid::>(bid:Bid):Boolean -- _gt is our name for > pre : not bid.oclIsUndefined()

Invariants

Invariants are conditions that are always true. They are always true. Think conservation of energy, not the color of the sky is blue.

Invariants

If an invariant is violated something is wrong with the implementation of your system. What are some invariants in our domain?

Example Invariants
context Auction inv : self.expires() > self.start context Bid inv : self.amount.amount > 0.0 /* Note this could be specified in the Auction context, but dont. */

Postconditions

Postconditions are the conditions that your operation guarantees will be true when it has completed. The contract: You meet the preconditions and Ill meet the postconditions.

PostConditions
context Auction::placeBid(bidder:Id, bid:Money) post: self.currentBid().amount = bid
Notice that the postcondition assumes serial or single-threaded execution. This postcondition isnt necessarily enforceable in an unprotected multi-threaded context.

PostConditions
context Auction::placeBid(bidder:Id, bid:Money) post : self.currentBid() > self.currentBid@pre()
Postconditions can reach back in time. @pre references the value before the operation. Another way to state a precondition

Implementing PostConditions
public void placeBid(Id bidder, Money bid) { Bid preCurrentBid = this.currentBid(); if (this.currentBid() <= preCurrentBid) {

OCL Contracts

Add more formal specifications to your models. Specify what will happen, without the how. Start at component boundaries. You can start out with simple contracts.

OCL Topics
Object Constraint Language (OCL)
OCL for Design by Contract OCL for Queries

Another OCL Example

OCL as Query Language


You can think of OCL as equivalent to SQL when it comes to querying object models.
Borlands ECO framework uses OCL for querying (as well as constraints, derived values, etc.)

Other query alternatives include OQL and Xquery

Test Results Mini Domain


Below is a simple domain for describing test results from test sessions at a competition for teams of logicians. This is our domain for examining OCL queries.

Example Test Data Set


Heres some example test result data from a logician competition.

Derived Values
context TestResult::compositeScore : Integer derive: (2 * logicScore) + illogicScore

OCL Collection Operations


context TestSession::numberOfResults : Integer derive: results->size()

OCL Collection Choices


Set: no duplicates, not ordered, result of navigating on association OrderedSet: not sorted, just ordered
Bag: may contain duplicates, not ordered, usually the result of navigating multiple associations Sequence: an ordered Bag

OCL Collections Classification


Duplicates No Duplicates

Not Ordered

Bag

Set

Ordered

Sequence

OrderedSet

OCL select() Query


context TestSession::numberOfScoresOverTarget( target : Integer) : Integer body: results->select( compositeScore > target)->size()

Translating OCL Queries


Lets look at what a transformation tool might do with one of our queries in SQL. SELECT COUNT(*) FROM test_results WHERE composite_score > :target;
team Blue Blue Red Green Red Blue logic_score 24 24 35 18 49 37 illogic_score 47 32 23 50 44 42 composite_score 95 80 93 86 143 116 name A Appell B Barry C Cross D Dolly E Elms F Fisher

Returning a Collection
context TestSession::testResultsForTeam( testTeam : Team) : Set(TestResult) body: results->select(team = testTeam)

Building Up Queries
context TestSession::averageScoreForTeam( testTeam : Team) : Real body: testResultsForTeam(testTeam).compositeScore ->sum() / testResultsForTeam(testTeam)->size()

Which Logicians Won?


context TestSession::bestResults() : Set(TestResult) body: results->select(compositeScore = results->sortedBy(compositeScore) ->last().compositeScore)

OCL Resources
The Object Constraint Language, 2ed Jos Warmer and Anneke Kleppe Klasse Objectens OCL page http://www.klasse.nl/ocl/ OCL 2.0 Specification at OMG http://www.omg.org/cgi-bin/doc?ptc/2003-10-14

Questions and Answers