I have a class diagram and I need to write some OCL about it but I'm not sure about the right syntax. I've searched a lot and found a lot of different ways, so I'd like to know if the way I'm going to write them is correct.
For example, in my class diagram I have the classes Ticket and Event linked by the role ticket validFor event. The ticket has a price attribute which is float. Is this way correct to write OCL to calcualte the total incoming of an event?
CONTEXT Event::totalIncoming():float
post result=ticket.allInstances()->select(t : t.validFor=self)->collect(price)->sum()
I'm taking all insances of tickets, selecting all instances valid for the event, collecting their prices and finally summing them.
The example you provide uses Complete OCL; a self standing text document, often with a
*.oclfile extension in which an Essential OCL expression is given a surrounding context as indicated by Section 12 of the OCL specification: "The Use of OCL Expressions in UML Models". This approach is helpful if you want to separate your constraint and model concerns and/or exploit the utility of bulk text editing.Alternatively you may use a tool that provides a text box for each UML Constraint. In this case you often enter just an Essential OCL expression that the tool wraps up in an appropriate way as a Constraint.body.
If working with Ecore, you may use OCLinEcore to embed Essential OCL expressions within the
*.ecoreor*.oclinecore.You example is wrong in that you should use lower case
context, and a:and optionally a name afterpost.Your example is probably wrong in that you use
ticketrather thanTicketthe class name.Your example is undesirable in that you use
allInstanceswhich should be avoided wherever possible if you actually plan to execute the OCL.However perhaps you did mean
ticketas the collection member variable, in which case theallInstances()is wrong.ticket->select(...)is sufficient to select some of the ticket collection.I suspect that
result = ticket->select(validFor=self).price->sum()would do. However the reverse testing ofvalidForcould be redundant since the forward navigation is often sufficient with a check of the reverse navigation redundant.