Measuring Cognitive Complexity in Software

When you look at a piece of code, do you ever find yourself rereading the same page, or thinking that it could have been written differently to be easier on the eyes? It's moments like these that bring forth the concept of cognitive complexity. In this article, I'll delve into understanding, measuring, and reducing cognitive complexity in code to enhance readability.

Cognitive complexity, which is related how we grasp the functioning of the code in our minds, is one of the measurement criteria used to assess the readability of a piece of code (class, function). This concept also indicates how difficult it would be to test a piece of code. Having a low value for cognitive complexity is desired, as it indicates that the code is highly readable.

        Code Highlighting Example         

#include <iostream>

void myMethod(int value) {
  bool isCheck = true;
  for (int i = 2; i <= value; ++i) { // +1
    for (int j = 2; j < i; ++j) { // +2 (nesting = 1)
      if (i % j == 0) { // +3 (nesting = 2)
        isCheck = false;
        break;
      }
    }
    if (!isCheck) { // +2 (nesting = 1)
      break;
    }
  }
  if (isCheck) { // +1
    std::cout << "isCheck is true" << std::endl;
  } else { // +1
    std::cout << "isCheck is false" << std::endl;
  }
} // Cognitive Complexity 10
  
     

The use of cognitive complexity begins by assigning weights to structures such as for, if-else, switch, and while. The weight assigned depends on the developer, with a default value of 1 often used. The weight increases by 1 for nested loop structures.

Another important criterion to consider in its calculation is the consecutive processing of variables, which also increases cognitive complexity.

Code Highlighting Example

//...
a = 1; // Cognitive Complexity: x
a = a * 2; // Cognitive Complexity: y
a = a * 2; // Cognitive Complexity: z > y

Also, cognitive complexity is used for logical operators.


a && b && c && d  // CC : 1 

a || b || c || d // CC : 1 

a && b && c || d // CC : 2 


The calculation of cognitive complexity is performed with SonarQube. By setting a limit value within SonarQube, the analysis of the code is enabled.

To define this in SonarQube: Quality Gates > Add Condition > Cognitive Complexity

As a result, cognitive complexity, one of the analysis methods in SonarQube that measures complexity, helps improve code readability, prevent bugs, and write testable code. This, in turn, contributes to improving the quality of the software product.

Yorumlar