Configuration | Metrics The following samples show how cognitive complexity is calculated. Sample: Control flow Statements that manipulate the control flow increase the cognitive complexity by 1. IF TRUE THEN //+1 cognitive complexity ; END_IF WHILE TRUE DO //+1 cognitive complexity ; END_WHILE FOR i := 0 TO 10 BY 1 DO //+1 cognitive complexity ; END_FOR REPEAT //+1 cognitive complexity ; UNTIL TRUE END_REPEAT The code snippet has a cognitive complexity of 4. Sample: Nesting of the control flow When nesting the control flow, an increment of 1 is added for each level of nesting.
IF TRUE THEN //+1 cognitive complexity WHILE TRUE DO //+2 (+1 for the loop itself, +1 for the nesting inside the IF) FOR i := 0 TO 10 BY 1 DO //+3 (+1 for the FOR loop itself, +2 for the nesting inside the WHILE and the IF) ; END_FOR END_WHILE REPEAT //+2 (+1 for the loop itself, +1 for the nesting inside the IF) ; UNTIL TRUE END_REPEAT END_IF The code snippet has a cognitive complexity of 8. Sample: Boolean expression Since Boolean expressions play a major role in understanding source code, they are also taken into account when calculating cognitive complexity.
Understanding Boolean expressions that are connected with the same Boolean operator is not as difficult as understanding a Boolean expression that contains alternating Boolean operators. Therefore, each chain of equal Boolean operators in an expression increases the cognitive complexity. b := b1; //+0: a simple expression, containing no operators, has no increment The simple expression without operator has an increment of 0. b := b1 AND b2; //+1: one chain of AND operators The expression with an AND operation has an increment of 1. b := b1 AND b2 AND b3; //+1: one more AND, but the number of chains of operators does not change The expression has an AND more.
But since it is the same operator, the number of chains formed with identical operators does not change. TE1200 101 Version: 2.11.1