Constraints

UML isn't very expressive. It's hard to say in UML something like:

Half of the employees are female

The discount rate is 3% of the monthly income

To get around this limitation, UML allows methods and classes to be annotated with constraints. A constraint is a Boolean condition that must evaluate to true in order for an object diagram to instantiate a class diagram.

Constraints can be written in English or they can be Boolean expressions in some language like Java or they can be written in OCL.

The Object Constraint Language: OCL

OCL is used to express invariant conditions of classes and pre and post conditions of operations.

Assume N1 and N2 are numbers, then:

N1 < N2
N1 + N2 = 0

are examples of OCL expressions.

Assume C1 and C2 are conditions and V1 and V2 are values (objects, strings, numbers, Booleans, etc.) then the following are OCL expressions:

C1 and C2
C1 or C2
C1 implies C2
not C1
V1 = V2
if C1 then V1 else V2 endif

End of line comments are preceded by two dashes:

-- this is a comment

OCL collections include sets, bags, and sequences. A collection has many properties. The property of a collection can be accessed using the arrow operator:

collection->property

For example:

c->size
c->isEmpty

We can select all elements x in a collection c that have a property P as follows:

c->select(x|P)

Note that this results in a new collection.

We can ask if all elements in a collection have property p

c->forAll(x|P)

Assume C is the set {3, 4, 5}:

C->forAll(x|0 < x and x < 6) -- = true
C->size > = 3 –- = true
C->isEmpty –- = false
C->select(x|x < 5) –- = {3, 4}

If we can express that an object v is an instance of a class C or a subclass of D:

v.oclIsTypeOf(C)
v.oclIsKindOf(D)

Example

We can represent constraints in a class diagram as notes surrounded by curly braces:

xxx

Here's the interpretation of the above constraints:

A graduate student's GPA must be at least 3.0

Context: Graduate
inv: self.gpa >= 3.0

An undergraduate student's GPA must be at least 2.0

Context: Undergraduate
inv: self.gpa >= 2.0

The title of a male student is Mr. otherwise it's Ms

Context: Student
inv: self.title = (if self.gender = MALE then "Mr" else "Ms" endif)

All university students are older than 16

Context: University
inv: self.students->all(s|s.age > 16)

A university has no more than 5000 students

Context: University
inv: self.students.size <= 5000

Exactly half of the students at a university are female:

Context: University
inv: self.students->select(v|v.gender = FEMALE)->size = self.students->size/2

Exactly half of the students at a university are graduate students

Context: University
inv: self.students->select(v|v.oclIsTypeOf(Graduate))->size = self.students->size/2

References

The Object Constraint Language (OCL) Specification

A good OCL Tutorial

http://www.csci.csusb.edu/dick/samples/ocl.html