OCL tips and tricks

Posted on in Blog
Acceleo is entirely based on OCL (Object Constraint Language) for all of its model navigation syntax. Though we did simplify it as much as possible for Acceleo (getting rid of redundant casts, increasing the standard library, overriding operators, ...), there are still some things that might cause problems to any beginning user.

Here are a few of the most unsettling language particularities :

Operations or features conflicting with reserved OCL keywords (UML anyone?). For example, if your model has a class "Operation" with a feature named "body", then writing "myClass.body" in OCL will result in a somewhat cryptic error : "invalid token 'body'".

The trick to access such features in OCL is to prefix the feature name with an underscore. For this example, you should have written "myClass._body".

For the record, the full list of OCL reserved keywords as per the last available OCL version, 3.0, is as follows :

andbody
contextdefderive
elseendifendpackageifimpliesininit
invletnotorpackagepostprestatic
thenxor

Accessing enumeration values. This might sound obvious to OCL experts, but how would one compare feature values to set enumerated values? The trick here is to qualify the access. For example if you wish to check that an UML operation's visibility is "public", here is what you would do in Java : "if (operation.getVisibility() == VisibilityKind.PUBLIC".

The OCL equivalent is "if (operation.visibility = VisibilityKind::public)".

There is no "elseif" in OCL ; remember to close each individual if properly with endifs : "if (...) then ... else if (...) then ... else ... endif endif"I believe these are the most annoying (as in "the most subject to cause weird compilation errors") OCL features ; don't hesitate to add yours :p.
Auteur d'origine: Laurent