code pal for ABAP > Documentation > Prefer CASE to ELSE IF
Conditions with many branches, i.e. IF
statements with many ELSEIF
alternatives, are often hard to read. When applicable, a CASE
statement where all branches are on equal footing as WHEN
branches is often much more readable.
The check reports a finding when the number of branches exceeds a configurable threshold.
The check finds IF
-ELSEIF
chains where each condition consists only of a single logical expression and the first token of all logical expressions is the same.
Use CASE
instead of ELSEIF
for multiple alternative conditions.
In exceptional cases, you can suppress this finding by using the pseudo comment "#EC PREFER_CASE
.
IF type = type-some_type. "#EC PREFER_CASE
" ...
ELSEIF type = type-some_other_type.
" ...
ELSE.
RAISE EXCEPTION NEW /dirty/unknown_type_failure( ).
ENDIF.
Before the check:
IF type = types-some_type.
" ...
ELSEIF type = types-some_other_type.
" ...
ELSE.
RAISE EXCEPTION NEW /dirty/unknown_type_failure( ).
ENDIF.
After the check:
CASE type.
WHEN type-some_type.
" ...
WHEN type-some_other_type.
" ...
WHEN OTHERS.
RAISE EXCEPTION NEW /clean/unknown_type_failure( ).
ENDCASE.