Cognitive complexity
The cognitive complexity of a function says how hard its flow is to follow, read from top to bottom. Each if, loop or catch breaks the line you read along, and a break inside another one makes you keep the outer condition in mind too: a break three levels down costs more than three breaks side by side.
It is one of the five metrics of a function.
How it is counted
Section titled “How it is counted”A function starts at 0. Each break in its linear flow adds to it, and a break adds more the deeper it stands.
The level is 0 in the body of the function; what a construct runs stands one level deeper than the construct. What an if tests, what a switch tests and what a loop iterates stand at the level of their statement, and so do the pattern and the guard of a case.
| Construct | Adds | What stands one level deeper |
|---|---|---|
if statement, with or without case; if element of a collection literal |
1 + its level | its branch, and its else branch |
else if |
1 | its branch; it goes on with the chain at the level of the first if |
else, of a statement or of an element |
1 | its branch |
conditional expression c ? a : b |
1 + its level | a and b |
switch statement or switch expression, as a whole |
1 + its level | the body of each case, the value of each case |
for, for-in, await for, while, do; a for element |
1 + its level | its body, its element |
catch clause, with or without on |
1 + its level | its body |
a run of && or of || |
1 for each run | — |
break or continue to a label |
1 | — |
A run is read over one logical expression: its && and || from left to right, with parentheses and ! between them. Each change of operator starts a new run. a && b && c adds 1, a && b || c 2, a || b && c || d 3, at any level. A logical expression inside another one, such as an argument of a call, is one of its own.
These add nothing:
- the body itself;
tryandfinally, whose bodies stay at the level of thetry; a block; - a
case, adefaultor a wildcard case by itself; ??,??=,?.,?.., a!after a value,await,return,throw,rethrow, andbreakandcontinuewithout a label;- an
assert, its condition included, as it is not in a release build; - a cascade;
- the
||and&&of a pattern (the alternatives of one case); - a call of the function itself: assay’s metrics are read from the parse alone, which does not say what a call calls.
As for every metric, a local function or closure is measured alone, so each callback of a Flutter build method has its own value. A constructor’s initializers count with its body, at level 0.
The page of the limit rule has the same rules beside its examples: How it is counted.
Example
Section titled “Example”int stock(List<Shelf> shelves, {required bool countReserved}) { var total = 0; for (final shelf in shelves) { if (shelf.isClosed) continue; for (final box in shelf.boxes) { if (box.isEmpty || box.isDamaged) { continue; } else if (box.isReserved && !countReserved) { continue; } total += box.items; } } return total;}Its cognitive complexity is 11:
| Construct | Level | Adds |
|---|---|---|
the outer for |
0 | 1 |
if (shelf.isClosed) |
1 | 2 |
the inner for |
1 | 2 |
if (box.isEmpty …) |
2 | 3 |
the run of || |
1 | |
else if |
1 | |
the run of && |
1 | |
each continue, which has no label |
0 |
The same function has a cyclomatic complexity of 8 and a nesting depth of 3.
Compared with the other two complexity metrics
Section titled “Compared with the other two complexity metrics”| Code | Cyclomatic | Nesting depth | Cognitive |
|---|---|---|---|
a flat switch of ten cases |
11 | 1 | 1 |
sixteen comparisons joined by || |
16 | 0 | 1 |
an if on a && b && c && d |
5 | 1 | 2 |
an if, three else if and an else |
5 | 1 | 5 |
three nested ifs, a conditional expression in the innermost |
5 | 3 | 10 |
a for in a for, an if in that and a while in the if |
5 | 4 | 10 |
five nested fors |
6 | 5 | 15 |
The three agree on deep code that branches. Only cyclomatic complexity is high on a flat switch or a long chain of one operator, which read easily. Only nesting depth is high on simple statements that stand deep. Only cognitive complexity catches code of moderate depth with many breaks, which may be under the other two limits.
The limit rule is max_cognitive_complexity, advisory: a function whose value is over the limit max is a violation of it. A function exactly at max is not reported.
| Preset | Limit |
|---|---|
core |
none: the preset does not hold the rule |
recommended |
none: the preset does not hold the rule |
strict |
15 |
strict gives the rule its limit with no exclude for the test directories.
To change the limit, set the rule’s max (Configuring metrics):
assay: rules: max_cognitive_complexity: max: 20Where this rule reports a function, it takes over the violations of max_cyclomatic_complexity and max_nesting_depth at that function, so that the function carries one violation (Over the limit, suppressed, taken over).
In the report
Section titled “In the report”assay metrics gives the metric a row in the box Metrics and a box of its own, with the limit and the counts on the right of its top line and the highest values first. Under recommended and core the row shows the limit none. assay metrics shows the report.
- JSON: the key
cognitiveComplexityof each function, with itsvalue, itslimitand whether it is over it. - HTML: the column Cognitive of the table of functions.
- Trend: the series Cognitive complexity over limit, at the points that give the metric a limit, and Mean cognitive complexity, the sum over the number of functions measured (Points and series).