Komplexität (McCabe)

Titel Kurzform

McCabe

Kategorien

Testbarkeit

Definition

Anzahl der Binärverzweigungen im Kontrollfluss der POU

(beispielsweise die Anzahl an Verzweigungen bei IF- und CASE-Anweisungen sowie Schleifen)

Weitere Informationen

Die zyklomatische Komplexität nach McCabe ist ein Maß für die Lesbarkeit und Testbarkeit von Quellcode. Sie wird durch Zählen der Anzahl der Binärverzweigungen im Kontrollfluss der POU berechnet. Die zyklomatische Komplexität bestraft eine hohe Verzweigung, da eine hohe Verzweigung die Anzahl der für eine hohe Testabdeckung benötigten Testfälle erhöht.

Empfohlene Obergrenze

10

Die folgenden Beispiele zeigen, wie die Komplexität nach McCabe berechnet wird.

Beispiel: IF-Anweisung

// 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

Der Codeschnipsel hat eine zyklomatische Komplexität von 4.

Beispiel: CASE-Anweisung

// 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

Der Codeschnipsel hat eine zyklomatische Komplexität von 4.

Beispiel: Schleifenanweisung

// 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

Der Codeschnipsel hat eine zyklomatische Komplexität von 4.

Beispiel: Andere Anweisungen

Auch die folgenden Anweisungen führen zu einer Erhöhung der zyklomatischen Komplexität:

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';

Der Codeschnipsel hat eine zyklomatische Komplexität von 3.