If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance. We can think of using a switch statement instead of multiple if-else if possible, or refactor code to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic". Switch statement has a performance advantage over if – else.

Functional rules

  • one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs :

  • IF and ELSEIF statements use explicitly variable names !

  • ELSE statements use implicity variable names !

  • one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels

  • we can assume that if one variable is used three times or more, we should :

  • use a SWITCH statement instead

  • or refactor the code if possible

Non-compliant Code Example

NON compliant, because nb is used 4 times : - 2 explicit times in IF statements - 2 implicit times in ELSE statements

int index = 1;
int nb = 2;
...
if (nb == 0) {
    nb = index;
} else if (nb == 1) {
    nb = index * 2;
} else if (nb == 2) {
    nb = index * 3;
} else {
    nb = -1;
}
return nb;

Compliant Code Example

SWITCH statement solution + refactor solution

int index = 1;
int nb = 2;
...
switch (nb) {
    case 0:
    case 1:
    case 2:
        nb = index * (nb + 1);
        break;
    default:
        nb = -1;
}
return nb;