max_cognitive_complexity
Reports a function whose cognitive complexity is over the limit. Flatten it with early returns, or move parts into functions with a name.
- Tier
- advisory
- Scope
- Dart
- Fix
- none
What it reports
Section titled “What it reports”A function whose flow, read from top to bottom, is harder to follow than the limit max allows. A function exactly at max is not reported. The violation is on the function’s name, and its message also gives the function’s cyclomatic complexity and nesting depth:
This function has a cognitive complexity of 13, which is over the limit of 8; its cyclomatic complexity is 8 and its nesting depth 4.
- What adds to it: each
if, conditional expression,switch, loop andcatchadds 1 and its nesting level; anelseorelse ifadds 1; each run of&&or of||adds 1. See How it is counted. - What is measured: every top-level function, method, getter, setter, operator and constructor with a body, factory constructors included. Each local function and closure is measured alone and adds nothing to the function around it: the callbacks of a
buildmethod count on their own. A closure’s violation is on its parameter list:(item)initems.where((item) { … }). - One violation, not three: where this rule reports a function,
max_cyclomatic_complexityandmax_nesting_depthdo not, and this rule’s message gives their values instead.
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. Code written by an AI coding agent often grows this way, one more if or && at a time, and can stay under the cyclomatic and nesting limits. The rule is advisory because the number is a signal, not a proof.
Example
Section titled “Example”max: 8 (and a nesting limit of 3, which the function is over as well; only this rule reports it)String? couponFor(Customer customer, Cart cart) { if (customer.isMember) { for (final coupon in customer.coupons) { if (coupon.isValid && !coupon.isUsed) { if (cart.total >= coupon.minimum || coupon.isFlexible) { return coupon.code; } } } } else if (cart.total > 100) { return 'WELCOME'; } return null;}Its cognitive complexity is 13: the if 1, the loop 2, the if in it 3 and its && 1, the innermost if 4 and its || 1, the else if 1.
String? couponFor(Customer customer, Cart cart) { if (!customer.isMember) { return cart.total > 100 ? 'WELCOME' : null; } for (final coupon in customer.coupons) { if (fits(coupon, cart)) return coupon.code; } return null;}
bool fits(Coupon coupon, Cart cart) => coupon.isValid && !coupon.isUsed && (cart.total >= coupon.minimum || coupon.isFlexible);The customer who is not a member leaves early, and what makes a coupon fit has a name: couponFor is 6, fits 2.
Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
max |
none in the rule; a preset gives it | The highest cognitive complexity a function may have. A whole number, zero or more. |
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
The rule has no limit of its own. Only strict switches it on, with max: 15; core and recommended do not hold it. To change the limit:
assay: rules: max_cognitive_complexity: max: 20Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression. It goes above the function’s name, where the violation is, or at the end of that line:
// The states follow the protocol's table, one branch for each.// ignore: assay/max_cognitive_complexityFuture<void> handle(Message message) async {// ignore_for_file: assay/max_cognitive_complexity silences it in a whole file, and // ignore: max_cognitive_complexity without the prefix works too. See Suppressions.
Details
Section titled “Details”All cases
How it is counted
Section titled “How it is counted”A function starts at 0, and each break in its flow adds to it. The level is 0 in the body of the function; the code a construct runs is one level deeper than the construct. What an if or 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 |
|---|---|
an if statement, with or without case, and an if inside a collection literal |
1 and its level |
an else if |
1: it goes on with the chain at the level of its first if |
an else, of a statement or inside a collection literal |
1 |
a conditional expression condition ? a : b |
1 and its level |
a switch statement or a switch expression, as a whole, however many cases it has |
1 and its level |
a loop: for, for-in, await for, while, do, and a for inside a collection literal |
1 and its level |
a catch clause, with or without on |
1 and its level |
a run of && or of || |
1 for each run |
a break or a 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 adds 2.
These add nothing:
- a
tryand afinally, whose bodies stay at the level of thetry, and a block; - a case, a
defaultor a wildcard case by itself; ??,??=,?.,?.., a!after a value, and a cascade;await,return,throw,rethrow, and abreakorcontinuewith no label;- an
assert, its condition included, since it is not in a release build; - the
||and&&of a pattern, which are the alternatives of one case; - a call of the function itself.
A constructor’s initializers count with its body, at level 0. A function with no break is 0, and so is a declaration with no body.
So this function has cognitive complexity 10:
int score(List<Answer> answers, {required bool strict}) { var total = 0; for (final answer in answers) { // 1: a loop at level 0 if (answer.isBlank) continue; // 2: an if at level 1 if (answer.isRight && !answer.isLate) { // 2: an if at level 1, and 1 for the run of && total += strict ? 2 : 1; // 3: a conditional expression at level 2 } else { // 1: an else total -= 1; } } return total;}A function declared inside another one has its own cognitive complexity and adds nothing to the function around it, as for every metric of assay. So the callbacks of a Flutter build method are measured each alone, and a build that only passes them on stays low. The metrics count it the same way and show the value of every function.
The other two complexity rules and the takeover
Section titled “The other two complexity rules and the takeover”max_cyclomatic_complexity counts the decisions of a function, and max_nesting_depth how deep its statements stand. All three report on the function’s name, and they often agree:
| Code | Cyclomatic | Nesting depth | Cognitive |
|---|---|---|---|
a flat switch of ten cases and a default |
11 | 1 | 1 |
sixteen comparisons joined by || |
16 | 0 | 1 |
an if, three else if and an else |
5 | 1 | 5 |
a for in a for, an if in that and a while in the if |
5 | 4 | 10 |
five nested fors |
6 | 5 | 15 |
So that a function over two or three of these limits gets one violation and not three, this rule takes over the other two. Where it reports a function, max_cyclomatic_complexity and max_nesting_depth do not report that function, and this rule’s message gives their values instead. A function over only the cyclomatic or the nesting limit, such as a flat switch or a long chain of one operator, is still reported by that rule.
The other two report as usual wherever this rule does not judge the file: where the preset does not switch it on, with enabled: false, in a path of its exclude, and where no limit is in effect for it. Both hosts decide this the same way, before any suppression. max_function_length, max_parameters and max_widget_nesting are never taken over.
On strict, the version that brings this rule turns the two violations at such a function into one of this rule. Their baseline entries no longer match, and the next assay baseline update drops them. The new violation is advisory, so no gate fails for it.
assay metrics shows a value this rule takes over as taken over: over its limit, but not reported by check (see the metrics).
The limit
Section titled “The limit”There is no exclude for the test directories.
Where no limit is in effect, the rule reports nothing and the other two complexity rules report every function over their limits. max: 0 reports every function that has a break at all.
The rule is advisory: a few deep loops over a grid can be plain, and a domain with many cases can push an easy function over the limit.