OCL Example: Companies and Employees
Please click on
this link
to view the according class diagram.
Now let's assume, your business analysts would like to capture the following
business rules to make sure the system behaves properly:
-
"If a person is male he can't have a husband and if he has a wife it must be female.
If a person is female, she can't have a wife and if she has a husband it must be male."
-
"No employee may be older than 65 years."
-
"If a person is employed at a company, it is not unemployed."
How can you add this kind of information to your model, precise, unambiguous
and with the possibility to realize deviations from the underlying classes?
Only OCL provides this capability.
With OCL, these rules could be written like this:
"If a person is male he can't have a husband and if he has a wife it must be female.
If a person is female, she can't have a wife and if she has a husband it must be male."
context Person
inv: wife->notEmpty() implies
(wife.gender = Gender::female and gender = Gender::male)
inv: husband->notEmpty() implies
(husband.gender = Gender::male and gender = Gender::female)
"No employee may be older than 65 years."
context Company
inv: self.employee->forAll(age <= 65)
"If a person is employed at a company, it is not unemployed."
context Company
inv: employee->exists(isUnemployed) = false