What is Cognitive Complexity and how to use it ?

Introduction

In the domain of software development, the Cognitive Complexity could be approximately defined as “the difficulty for a human being to understand some code snippet”. This definition seems to be clear and without ambiguities, but it is not.

What is the purpose of the Cognitive Complexity ?

The understandability of the code is probably the most important component of the maintainability of a software. It is hard and painful to add features or fix bugs in a code which is difficult to understand, especially if it’s not you which wrote it. A non-understandable code is a dead code.

How to measure the Cognitive Complexity ?

The research area around the idea of cognitive complexity is active and fertile since more than 20 years. Unfortunately, the definition of this concept is different for each author, which leads to a lot of confusion. Given that the concept itself is not well-defined, each researcher uses its own definition, and his own measurement technique.

The Cognitive Complexity for SonarQube©

The tool

SonarQube© is probably the most well-known open-source software quality tool (and my favourite). As far as I know, it’s the only one which uses explicitly the concept of Cognitive Complexity. They explain how they measure it in a document called Cognitive complexity: a new way to measure understandability written by Ann Campbell for the SonarSource© company in 2017. I will explain now its main ideas.

function myMethod(): void {
try {
if (condition1) { // +1
for (int i = 0; i < 10; i++) { // +2 (nesting=1)
while (condition2) { … } // +3 (nesting=2)
}
}
} catch (err) { // +1
if (condition2) { … } // +2 (nesting=1)
}
} // Cognitive Complexity = 9
let name: string;
if (a) { // +1
name = a.name;
} // Cognitive Complexity = 1


let name: string;
name = a?.name; // Cognitive Complexity = 0

Is SonarQube©’s cognitive complexity score relevant ?

First, let’s remember the most important: cognitive complexity is a notion relative to human cognition. Consequently, we will never be able to write an algorithm which will return a score reflecting the exact value of the cognitive complexity (defined as above). Never. We maybe could calculate a good approximation of the time needed to understand some code snippet, but never an exact value. This point is probably the most important of this article.

Limitations of the SonarQube©’s algorithm

A problem of weight
First, let’s remember the main idea of the SonarQube©’s algorithm: it is more difficult to understand an if which is nested in another if than an if which is alone. That’s not proven, but we can reasonably think that it is true.

if (a > 0) {      // +1
if (b > 0) { // +2 (nesting=1)
// Do something
}
} // Cognitive Complexity = 3
// First code snippetif (a > 0) { ... } // Cognitive Complexity = 1
// Second code snippet
if (this.someMethod(a) > this.someProperty[2] + this.otherProperty) { ... } // Cognitive Complexity = 1
let a = 1; // Cognitive Complexity: x
a = a * 2; // Cognitive Complexity: y
a = a * 2; // Cognitive Complexity: z > y
function hyperComplex<T>(object: Object, path: string | string[] = '', value: any): CallbacksMock<T> {
path = path.toString().match(/[^.[\]]+/g);
path.slice(0, -1).reduce((acc: any, curr: any, index: number) => {
const arg = Math.round(index) % 3;
acc(0);
return Object(acc[curr]) === acc[curr + arg][0];
}, object)[path[path.length - 1]] = value;
return new CallbacksMock<T>(object);
}

Should we use SonarQube©’s Cognitive Complexity score ?

Yes, of course ! Their algorithm is not perfect, that’s sure, but as far as I know, it is the only open-source tool which gives an approximation of cognitive complexity.

Could we write a better algorithm ?

Absolutely ! It is not so difficult to add some rules to fix the problems described above. In fact, it will not be a real fix because, as we said, we will never be able to give the exact value of the cognitive complexity. However, we can add rules which will give us a better approximation of the reality.

Cognitive complexity detailed line by line

Acknowledgements

I’m not the only one which worked on the @genese/complexity module: many friends and colleagues helped me, and I want to thank all of them for the trust they placed in me, and for their contribution to the implementation of this module :

TypeScript expert. Specialization in static code analysis and in software complexity

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store