language-lawyerumlocl

UML Constraints


There are some Constraints defined on the UML Constraint type; among others, the not_apply_to_self() Constraint which prevents unwanted recursion (this is UML 2.5.1).

However, I am wondering if an invariant Constraint can also have pre- and post-conditions? This is often encountered in the body of Operations, but I couldn't find any instances of an invariant Constraint having one or more pre-conditions, although I think it might be useful WRT code re-use. Any pre- or post-conditions could presumably be built into the invariant part, however.

Would this be allowed in a valid model?


Solution

  • <rant>The Constraint class is a confused dustbin that avoids UML getting close to the detail that OCL needs. In UML 1.x there was another kind of stereotype that clarified roles. Why weren't distinct Precondition/Invariant etc classes defined for UML 2.x? Why does the OCL specification of Constraints provide such broken models?</rant>

    Since Constraint is a dustbin with ill-specified semantics for each distinct role, you are required to use your common sense to make sense of the standard roles and may of course use your ingenuity for custom roles.

    In practice I have come to recognize that an optimising OCL code generator should form all the constraints applicable to a particular context into a composite and-expression. The composite should be optimized to hoist common sub-expressions and prioritize simple/likely failures. This should avoid duplicate diagnostics and avoid complex constraints having to repeat many simple constraints as guards. e.g. I should not need to guard for a null-name when checking it's spelling if there is a separate constraint prohibiting null names.

    Your specific question seems to confuse roles. Conventionally, considering a single body language, a Class is only expected to have invariants. An Operation may have a body-specification (actually an expression) and any number of pre and post conditions. The latter should satisfy your pre/posts on the body. Neither Class nor Operation has 'constraints' although all the foregoing overload the Constraint class. A perverse (result = ...) idiom is required to model the logical body-expression as a body-specification.