Section 5.2. Constraints


5.2. Constraints

Sometimes 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:


Invariants

An invariant is a constraint that must always be true; otherwise the system is in an invalid state. Invariants are defined on class attributes.


Preconditions

A precondition is a constraint that is defined on a method and is checked before the method executes. Preconditions are frequently used to validate input parameters to a method.


Postconditions

A postcondition is also defined on a method and is checked after the method executes. Postconditions are frequently used to describe how values were changed by a method.

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(..) operation


In 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.

OCL allows you to specify all sorts of constraints that limit how your classes can operate. For more information on OCL, see Appendix A.





Learning UML 2.0
Learning UML 2.0
ISBN: 0596009828
EAN: 2147483647
Year: 2007
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net