Search code examples
constraintsoperationocl

OCL write constraint on an operation of class A and attribute of class B


Follwing another post:

I would like to know if OCL allows the following.

Imagine the following UML diagram.

How to use ocl to model: "a person can drinkWater() only if he is from country name 'ABCD'" AND if the population of the country is >= 1000000"

Of course, the example is purely fictive.

================                  ================
|    Person    |                  |    Country   |
|--------------|                  |--------------|
|- name        |------------------|- id          |
|- age         |                  |- name        |
|--------------|                  |- population  |
|+ drinkWater()|                  ================
|+ drinkBeer() |                  
================                   

Solution

  • You will need to name the role of Country (create a named attribute inside Person). So let's name that country. This of course can be used "as usual":

    context Person::drinkWater()
    pre Enough: self.country.name == "ABCD" and self.country.population >= 1000000