You use whenfalse in OCL when you want to perform an expression only when a Boolean condition evaluates to false; it is for modelers writing conditional behavior in MDriven expressions.
Syntax
booleanExpression.whenfalse(expressionToRun)whenfalse evaluates the Boolean expression on its left. When that result is false, it evaluates the expression in parentheses. The operator returns the result of the original Boolean expression.
| Condition result | What whenfalse does
|
Returned result |
|---|---|---|
true
|
Does not run the expression in parentheses. | true
|
false
|
Runs the expression in parentheses. | false
|
Validate and react to failure
Use whenfalse to keep the Boolean result while adding behavior for the failure case.
For example, if isValid is false, the expression below shows an error message and still returns false. If isValid is true, it does not show the message and returns true.
isValid.whenfalse(ShowErrorMessage)This pattern is useful when the caller must continue to receive the validation result after the failure behavior has run.
Use with enum comparisons
You can store a value in a let variable and attach behavior to Boolean comparisons:
let x = SomeObject.SomeEnum in
(x = #Enum1).whenfalse(SomeObject.DoYourThing1)In this example, SomeObject.DoYourThing1 runs when x is not #Enum1. The complete expression returns whether x = #Enum1.
Chaining conditions
You can place multiple whenfalse expressions in a sequence separated by semicolons:
let x = SomeObject.SomeEnum in
(
(x = #Enum1).whenfalse(SomeObject.DoYourThing1);
(x = #Enum2).whenfalse(SomeObject.DoYourThing2);
(x = #Enum3).whenfalse(SomeObject.DoYourThing3)
)Read this carefully: each action runs when its own comparison is false. For example, when x is #Enum1, the first action does not run, but the second and third comparisons are false, so their actions can run. Use this form only when that is the intended behavior.
Related operator
whenfalse is the inverse conditional form of whentrue, which runs its expression when the Boolean condition is true. For the broader set of logical operators, see Documentation:OCL Boolean Operators.
