You use the if operator in OCL to return one value when a condition is true and another value when it is false.
How if works
An if expression evaluates a condition first. It then returns the result from one of two branches:
| Part | Purpose | Car example |
|---|---|---|
| Condition | The expression that evaluates to true or false. | Test whether the selected Car is missing. |
| True branch | The result returned when the condition is true. | Return a message that no car exists. |
| False branch | The result returned when the condition is false. | Return a message that a car exists. |
Example: handle a missing Car
Assume that an expression selects the first object from the collection of all Car instances. If no Car exists, that selected value is null.
Use isNull as the condition. When it returns true, return a message for the missing value; otherwise, return the message for an existing value.
| Selected first Car | isNull result
|
if result |
|---|---|---|
| No Car exists | true | A message stating that no car exists |
A Car exists, for example a Car with Name set
|
false | A message stating that a car exists |
This pattern prevents later expressions from treating a missing object as though it were available. For the opposite test, use notNull.
When to use it
Use an if expression when the value you return depends on a condition. For example:
- Return different text depending on whether a selected Car exists.
- Select a fallback value when an attribute or object has no assigned value.
- Return different results after evaluating a true-or-false collection condition, such as forAll.
