5.2. ConstraintsSometimes you will want to restrict the ways in which a class can operate. For example, you might want to specify a class invariant a rule that specifies that a particular condition should never happen within a classor that one attribute's value is based on another, or that an operation should never leave the class in an irregular state. These types of constraints go beyond what can be done with simple UML notation and calls for a language in its own right: the OCL. There are three types of constraint that can be applied to class members using OCL:
Constraints are specified using either the OCL statement in curly brackets next to the class member or in a separate note, as shown in Figure 5-10. Figure 5-10. Three constraints are set on the BlogEntry class: self.url>notEmpty( ) and rating>=0 are both invariants, and there is a postcondition constraint on the updateRating(..) operationIn Figure 5-10, the url attribute is constrained to never being null and the rating attribute is constrained so that it must never be less than 0. To ensure that the updateRating(..) operation checks that the rating attribute is not less than 0, a precondition constraint is set. Finally, the rating attribute should never be more than 5 after it has been updated, so this is specified as a postcondition constraint on the updateRating(..) operation.
|