Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Modeling Practice

OCL Constraints

Learn the Object Constraint Language: invariants, preconditions, postconditions, navigation and collection operations, and how to check them in code.

A class diagram says that an Order has many OrderLines and that an Account has a balance. It cannot say that the balance must never be negative, that an order needs at least one line, or that a customer under 18 cannot buy alcohol. Rules like these are called constraints. UML lets you write them in plain language, but plain language is ambiguous. The Object Constraint Language (OCL) is a small, formal, side-effect-free language for expressing them precisely, so that humans, tools and tests agree on what they mean.

OCL is not a programming language: an expression only reads the model and returns a value. It never changes anything.

Where OCL is used

  • Invariants: conditions that must be true for every instance of a class at all stable times.
  • Preconditions: what must hold before an operation is called.
  • Postconditions: what the operation guarantees afterward.
  • Initial and derived values: init for starting values, derive for computed attributes.
  • Guards in state machines and query operations (body).

All of them are written inside a context, which names the class and the element the expression is about.

Invariants

TEXT
context Account
inv nonNegative: self.balance >= 0

context Order
inv hasLines: self.lines->notEmpty()
inv totalMatches: self.total = self.lines->collect(l | l.price * l.qty)->sum()

self refers to the instance. The label after inv (nonNegative) is optional but makes error messages readable. -> calls an operation on a collection, while . navigates a property of a single object.

Preconditions and postconditions

TEXT
context Account::withdraw(amount : Real) : Boolean
pre  positiveAmount: amount > 0
pre  enoughMoney:    self.balance >= amount
post debited:        self.balance = self.balance@pre - amount
post result:         result = true

@pre accesses the value of a property before the call, and result is the return value. Together, pre and postconditions form a contract: the caller guarantees the precondition, the operation guarantees the postcondition. This is the idea behind design by contract (Eiffel), also visible in assert statements and modern libraries.

You navigate using the names of attributes and association ends:

TEXT
context Order
inv adult: self.customer.age >= 18 or not self.lines->exists(l | l.product.ageRestricted)

Navigating an association with multiplicity greater than one returns a collection, and OCL has four kinds: Set (no duplicates, unordered), Bag (duplicates, unordered), Sequence (ordered, duplicates), OrderedSet (ordered, unique).

Collection operations

Operation Meaning Example
size() Number of elements self.lines->size() <= 100
isEmpty(), notEmpty() Emptiness self.lines->notEmpty()
includes(x) Membership self.tags->includes('new')
select(expr) Filter self.lines->select(l | l.qty > 5)
reject(expr) Opposite of select self.lines->reject(l | l.free)
collect(expr) Map to a new collection self.lines->collect(l | l.price)
forAll(expr) Every element satisfies it self.lines->forAll(l | l.qty > 0)
exists(expr) At least one satisfies it self.lines->exists(l | l.free)
sum() Total of numbers self.lines->collect(l | l.price)->sum()
isUnique(expr) No duplicates self.lines->isUnique(l | l.product)
iterate(...) General fold rarely needed

You may recognize the same ideas as filter, map, all, any and reduce in modern languages.

Types and operators

OCL has Boolean, Integer, Real, String and the model's own types. Boolean operators are and, or, not, xor and implies. The implies operator is useful for conditional rules: a implies b is true when a is false or both are true.

TEXT
context Order
inv shipped: self.status = Status::Shipped implies self.shippingDate->notEmpty()

oclIsTypeOf(T), oclIsKindOf(T) and oclAsType(T) test and cast types; oclIsUndefined() tests for null.

Checking OCL-style rules in code

You do not need a special tool to benefit from OCL thinking. Translate each invariant into a function and check every instance. The first example checks invariants on a small order model.

Python Invariants as predicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Contracts: pre and postconditions

Preconditions and postconditions become checks at the start and end of a method. A decorator keeps them next to the operation without cluttering the body.

Python Design by contract with a decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical tips

  • Write constraints for rules that the diagram cannot express and that people argue about. Do not constrain the obvious.
  • Prefer small named invariants over one big one: failures then point to a cause.
  • Keep invariants about stable states; during a method an invariant may be broken temporarily.
  • Tools such as Eclipse OCL, USE and Dresden OCL parse and evaluate OCL against models. In everyday code the equivalent is validation annotations, asserts, database constraints and property-based tests.
  • A constraint on the diagram is also a test waiting to be written: each inv suggests at least one passing and one failing case.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does context Account inv: self.balance >= 0 express?

    inv defines an invariant for all instances of the context class.
  2. 2. What does self.balance@pre mean in a postcondition?

    @pre accesses the value of a property at the start of the operation.
  3. 3. Which expression checks that every line has a positive quantity?

    forAll requires every element to satisfy the predicate; exists needs only one.
  4. 4. What is the difference between '.' and '->' in OCL?

    Use the arrow for collection operations such as size, select and forAll.

Summary

  • OCL is a formal, side-effect-free language for precise constraints on UML models.
  • Invariants, preconditions and postconditions form contracts for classes and operations.
  • Navigate with . and use collection operations with ->: select, collect, forAll, exists, sum.
  • @pre, result and implies handle before/after and conditional rules.
  • Even without OCL tools, translate constraints into predicates, asserts and tests.

Next: Design Patterns in UML