OCL Syntax

The remainder of this chapter uses examples from the class diagram shown in Figure B-1.

Constraints on Classifiers

Each OCL expression must have some sense of context that an expression relates to. Often the context can be determined by where the expression is written. For example, you can link a constraint to an element using a note. You can refer to an instance of the context classifier using the keyword self. For example, if you had a constraint on Student that their GPA must always be higher than 2.0, you can attach an OCL expression to Student using a note and refer to the GPA as follows:

    self.GPA > 2.0
Example class diagram used in this chapter

Figure B-1. Example class diagram used in this chapter

It's important to realize that this OCL expression is an invariant, meaning the system would be in an invalid state if a student's GPA dropped to less than 2.0. If you want to allow a GPA of less than 2.0 and send out a letter to the student's parents in the event such a low GPA is achieved, you would model such behavior using a UML diagram such as an activity or interaction diagram.

You can follow associations between classifiers using the association end names as though they were attributes of the originating classifier. The following invariant on Course ensures that the instructor is being paid:

    self.instructor.salary > 0.00

If an association has a multiplicity of 0..1, you can treat the association end as a Set

Get UML 2.0 in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.