I just recently started to look deeper into the intricacies of OCL. During my first applications, the following question came up:
Is it possible, and if so, what is the correct way to derive an attribute in case that no value is provided?
Approaches that came to my mind, but which may be formally incorrect were:
context GenericClass::genericAttribute : PrimitiveType
derive: if genericAttribute.oclIsUndefined() then
<expression of matching type>
endif
Another approach I could think of was
context GenericClass::genericAttribute : PrimitiveType
inv: genericAttribute.oclIsUndefined implies genericAttribute = <expression of matching type>
Admittedly, both approaches appear to be a bit awkward and thus I'd be happy if you could show me the formally correct way.
The term 'derived' is unfortunately overloaded. I presume that your usage here has nothing to do with inheritance, which is not available for properties - you need to delegate to a derived operation. Rather I assume you mean an automated computation.
Your first example is cyclic and so should fail, probably with a stack overflow. The invariant will probably detect and fail rather than correct the unsatisfied condition although an OCL implementation with global control and symbolic capabilities might get it 'right' once you have got past the illegal startup transient.
If you cannot use an 'init' clause to initialize then I suggest that you add a genericAttribute() operation that performs a clean access. If you rename the persisted attribute as rawGenericAttribute then you can re=use the genericAttribute spelling as a derived computation and avoid the confusion of same named attributes and operations.
(It is rarely necessary to use x.oclIsUndefined(). x <> null is clearer.)