Name
IF-02: Use IF...ELSEIF only to test a single, simple condition
Synopsis
The real world is very complicated; the software we write is supposed to map those complexities into applications. The result is that we often end up needing to deal with convoluted logical expressions.
You should write your IF
statements in such a way as to keep them as straightforward and
understandable as possible. For example, expressions are often
more readable and understandable when they are stated in a
positive form. Consequently, you are probably better off avoiding
the NOT operator in conditional
expressions.
Example
It's not at all uncommon to write or maintain code that is structured like this:
IF condA AND NOT (condB OR condC) THEN
CALL proc1;
ELSEIF condA AND (condB OR condC) THEN
CALL proc2;
ELSEIF NOT condA AND condD THEN
CALL proc3;
END IF;It's also fairly common to get a headache trying to make
sense of all of that. You can often reduce the trauma by trading
off the simplicity of the IF
statement itself (one level of IF and ELSEIF conditions) for the simplicity of
clauses within multiple levels:
IF condA THEN
IF (condB OR condC) THEN
CALL proc2;
ELSE
CALL proc1;
END IF;
ELSEIF condD THEN
CALL proc3
END IF;Don't forget, by the way, to take into account the possibility of your expressions evaluating to NULL. This can throw a monkey wrench into your conditional processing.
Benefits
Following this best practice will make your code easier to read and maintain.
Breaking an expression into smaller pieces ...