Object Constraint Language (OCL)
Object Constraint Language
A class diagram shows which classes exist and how they are linked. Its multiplicities limit how many objects may be linked, but they cannot say that every line item's quantity must be positive, or that a withdrawal may not overdraw an account. The Object Constraint Language (OCL) is the textual companion to UML that states such rules precisely. You need it when a model must be checked, handed to another team, or turned into code with its rules intact.
Context, self and navigation
Every OCL constraint is written in a context: the class or operation it describes. Inside the constraint, self names the particular instance being checked. From self you navigate the model with a dot, using attribute names and the role names at the far end of associations.
Navigating a role with multiplicity *, such as self.lineItems, gives a collection. Collection operations use an arrow instead of a dot. OCL is a side-effect-free language: evaluating an OCL expression never changes the model. It only yields a value, usually a Boolean.
Operation | Returns | Meaning |
|---|---|---|
->size() | Integer | Number of elements |
->isEmpty(), ->notEmpty() | Boolean | Whether the collection has no elements, or at least one |
->sum() | Number | Total of numeric elements |
->select(cond) | Collection | The elements for which cond is true |
->forAll(cond) | Boolean | True when every element satisfies cond |
->exists(cond) | Boolean | True when at least one element satisfies cond |
Example: Suppose an Order is linked to three line items with quantities 2, 1 and 5. Then self.lineItems->size() evaluates to 3, self.lineItems.quantity->sum() evaluates to 8, and self.lineItems->forAll(quantity > 0) evaluates to true. Writing self.lineItems.quantity is shorthand for self.lineItems->collect(quantity), which gathers one value per element.
Invariants
An invariant is a Boolean condition that must be true for every instance of its context class whenever that instance is in a stable state, that is, between operation calls. Its general form is:
context ClassName
inv ConstraintName:
Boolean expression about selfThe note in the diagram is one: context Order inv PositiveQty: self.lineItems->forAll(quantity > 0). The multiplicity 1..* already guarantees that an order has at least one line item; the invariant adds a rule about attribute values that no multiplicity can express. Conditional rules use implies, as in context Order inv: self.status = 'paid' implies self.total > 0.
Operation contracts
An operation contract attaches a precondition (pre) and a postcondition (post) to an operation. The caller is responsible for the precondition; the operation guarantees the postcondition, but only if the precondition held when it was called. Two expressions exist only in postconditions: x@pre is the value of x at the moment of the call, and result is the value the operation returns.
context Account::withdraw(amount : Real) : Real
pre: amount > 0 and amount <= self.balance
post: self.balance = self.balance@pre - amount and result = self.balanceKind | Context | When it must hold | Who must make it true |
|---|---|---|---|
Invariant | A class | Every stable state of every instance | Every operation of the class |
Precondition | An operation | When the operation is called | The caller |
Postcondition | An operation | When the operation returns | The operation itself |
Example: An account with balance 250 receives withdraw(100). The precondition is true because 100 > 0 and 100 is at most 250. The postcondition then requires the new balance to equal 250 − 100 = 150 and the returned value to be 150.
What to remember
- Every constraint names a context; self is the instance being checked.
- Use a dot for attributes and navigation, and an arrow for collection operations such as size, sum, select and forAll.
- Multiplicities limit how many objects are linked; OCL states rules about values that a diagram cannot.
- An invariant holds in every stable state; a precondition binds the caller; a postcondition binds the operation.
- @pre and result appear only in postconditions.
- OCL expressions read the model and never change it.
Example: Checking a credit-limit contract
A shop models each Customer with a creditLimit : Real and the role orders to its Order objects. Each Order has a status of 'open' or 'paid' and a derived attribute total, an attribute whose value is computed from other values rather than stored:
context Order::total : Real
derive: self.lineItems->collect(quantity * unitPrice)->sum()
context Customer
inv OpenWithinLimit:
self.orders->select(status = 'open').total->sum() <= self.creditLimit
context Customer::placeOrder(o : Order)
pre: o.status = 'open' and
self.orders->select(status = 'open').total->sum() + o.total <= self.creditLimit
post: self.orders = self.orders@pre->including(o)Customer c1 has a credit limit of 500 and three orders:
Order | Status | Line items (quantity × unit price) |
|---|---|---|
o1 | paid | 2 × 40 and 1 × 25 |
o2 | open | 3 × 60 |
o3 | open | 1 × 150 and 4 × 20 |
a) Evaluate the invariant OpenWithinLimit for c1.
The select keeps only orders whose status is 'open', so o1 drops out even though it is linked to c1. For each remaining order, the derived total multiplies quantity by unit price for each line item and sums the products. The total of o2 is 3 × 60 = ________, and the total of o3 is 150 + 80 = ________. Navigating .total on the selected orders gives a bag of these two values, and ->sum() adds them to ________.
Comparing that open sum with the credit limit of 500 gives true, so the invariant holds for c1. Forgetting the select and adding o1 as well would give 515 and wrongly report a violation.
b) Before the call, c1 prepares a new open order o4 with line items 2 × 35 and 1 × 50. Evaluate the precondition of placeOrder(o4).
Both conjuncts must be true. The first holds because o4 is open. For the second, o4 has a total of 2 × 35 + 1 × 50 = ________. The open sum from part a plus this total is ________, which exceeds the credit limit of 500.
The precondition is therefore false. A caller must not invoke placeOrder in this state; if it does, the contract promises nothing about the outcome, so the postcondition cannot be relied on.
c) Instead, c1 places a new open order o5 with a single line item 5 × 17. Evaluate the precondition, then state what the postcondition requires for self.orders->size() after the call and whether OpenWithinLimit still holds.
The total of o5 is 5 × 17 = ________. Adding it to the open sum from part a gives 410 + 85 = 495, which is at most 500, so the precondition is true.
Before the call, self.orders@pre->size() is ________. Because o5 is a new object not already among c1's orders, including(o5) adds one element, so the postcondition requires self.orders->size() = 4 after the call.
After the call the open orders are o2, o3 and o5, whose totals sum to 495, still within 500, so OpenWithinLimit continues to hold. The precondition was written so that any call it permits preserves the invariant.
A training session has a property participants : Set(Person), and each person has an integer age. In the current snapshot, self.participants is empty. Complete each result using true or false under standard Object Constraint Language (OCL) semantics.
The expression self.participants->forAll(p | p.age >= 18) evaluates to .
The expression self.participants->exists(p | p.age >= 18) evaluates to .
The expression self.participants->notEmpty() and self.participants->forAll(p | p.age >= 18) evaluates to .
In a UML model, a Department has the attribute budget : Real and the association role employees (multiplicity 0..*) to Employee. Each Employee has salary : Real and the role department (multiplicity 1). The requirement is that the combined salaries of a department's employees must never exceed that department's budget. Which OCL constraint expresses this requirement?