CASE TRUE instead of cascading IF THEN ELSE

To make code easier to read when you want to perform some logic on the first TRUE condition that you encounter, instead of using cascading IF THEN ELSE, you can use a CASE TRUE statement (it works because a CASE enters the first block that has a condition that matches the criteria of the CASE).

All of the WHEN criteria must be code constructs that evaluates to a LOGICAL.
This trick works great for range conditions, but it can also be used in many other contexts.

DEFINE VARIABLE deSomePercentage AS DECIMAL NO-UNDO INITIAL 42.9.
DEFINE VARIABLE lAccept20And60   AS LOGICAL NO-UNDO INITIAL FALSE.

CASE TRUE:
  WHEN lAccept20And60 AND (deSomePercentage >= 20 AND deSomePercentage <= 60)
  THEN DO:
    /* do some logic */
  END.
  WHEN deSomePercentage > 20 AND deSomePercentage < 60
  THEN DO:
    /* do some logic */
  END.
  WHEN deSomePercentage > 60
  THEN DO:
    /* do some logic */
  END.
  OTHERWISE DO:
    /* do some logic */
  END.
END CASE.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mmniet's picture

CASE TRUE instead of cascading IF THEN ELSE

I performed some tests, but for more complex condition-testing, it's better to use the if-statement (when you look at performance :)).

furthermore it's an everlasting discussion to use the if or case for better readable code


tamhas's picture

I'll bet the performance

I'll bet the performance difference is trivial, so I would vote for readability.