Complexity (McCabe)

Title short form

McCabe

Categories

Testability

Definition

Number of binary branches in the control flow of the POU

(for example, the number of branches for IF and CASE statements and loops)

Further information

McCabe's cyclomatic complexity is a measure of the readability and testability of source code. It is calculated by counting the number of binary branches in the control flow of the POU. Cyclomatic complexity penalizes high branching because high branching increases the number of test cases required for high test coverage.

Recommended upper limit

10

The following samples show how complexity is calculated according to McCabe.

Sample: IF statement

// every POU has an initial cyclomatic complexity of 1, since it has at least 1 branch
IF b1 THEN                // +1 for the THEN branch
    ;
ELSIF b2 THEN             // +1 for the THEN branch of the IF inside the ELSE
    ;
ELSE
    IF b3 OR b4 THEN      // +1 for the THEN branch
        ;
    END_IF
END_IF

The code snippet has a cyclomatic complexity of 4.

Sample: CASE statement

// every POU has an initial cyclomatic complexity of 1, since it has at least 1 branch
CASE a OF
    1:     ;              // +1
    2:     ;              // +1
    3,4,5: ;              // +1
ELSE                      // the ELSE statement does not increase the cyclomatic complexity
    ;
END_CASE

The code snippet has a cyclomatic complexity of 4.

Sample: Loop statement

// every POU has an initial cyclomatic complexity of 1, since it has at least 1 branch
WHILE b1 DO               // +1 for the WHILE loop
    ;
END_WHILE
 
REPEAT                    // +1 for the REPEAT loop
    ;
UNTIL b2
END_REPEAT
 
FOR a := 0 TO 100 BY 2 DO // +1 for the REPEAT loop
    ;
END_FOR

The code snippet has a cyclomatic complexity of 4.

Sample: Other statements

The following statements also lead to an increase in cyclomatic complexity:

FUNCTION FUN : STRING
VAR_INPUT
    bReturn  : BOOL;
    bJump    : BOOL;
END_VAR
// every POU has an initial cyclomatic complexity of 1, since it has at least 1 branch
JMP(bJump) lbl;           //Conditional jumps increase the cyclomatic complexity by 1
 
FUN := 'u';
RETURN(condition_return); //Conditional returns increase the cyclomatic complexity by 1, too
 
lbl:
    FUN := 't';

The code snippet has a cyclomatic complexity of 3.