Appendix A. Object Constraint Language

Chapter 5 introduced writing constraints in your class diagrams using OCL. You don’t have to use OCL to express constraints—you can use your favorite programming language syntax or even natural language. This appendix discusses the advantages of OCL and provides more details about how to more use OCL.

Recall from Chapter 5 that a constraint is written in curly braces after the element it constrains or displayed in an attached note. Figure A-1 shows different ways of specifying that the attribute rating has to be non-negative.

Different ways of attaching and expressing a constraint
Figure A-1. Different ways of attaching and expressing a constraint

Figure A-1 shows that the words expressing a constraint can vary. Constraints can be written in natural language, such as:

rating is greater than or equal to zero

Constraints can also look like a programming language expression, such as:

rating >= 0

Because natural language can be ambiguous (and long-winded!), many modelers use syntax similar to their preferred programming language: notice that rating >= 0 looks like a Java or C expression.

Constraints can get more complicated; for example, they can specify that a value isn’t null. This means you have a lot of options for expressing constraints, so how do you decide which notion to use? Such an expression may look different in different programming languages. If constraints are expressed in a standard and predictable ...

Get Learning UML 2.0 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.