Skip to content

Cyclomatic complexity

The cyclomatic complexity of a function counts the decisions it makes. Each decision is another case to keep apart when you read the function, and another path that needs a test: a function of complexity 20 has at least twenty ways through it.

It is one of the five metrics of a function. A local function or a closure has a value of its own and adds nothing to the function around it.

A function starts at 1, and each branch point adds one:

  • each if: also else if, an if with a case, an if in a collection literal;
  • each loop: for, for-in, await for, while, do, a for in a collection literal;
  • each case of a switch statement or expression, each catch clause, each conditional expression;
  • each &&, || and ??.

An else, a default, a finally and a wildcard case _ add nothing. A constructor’s initializers count with its body.

The page of the limit rule has every case: How the complexity is counted.

String describe(Order? order, {String? fallback}) {
if (order == null) return fallback ?? 'no order';
for (final item in order.items) {
if (item.quantity <= 0 || item.price < 0) {
return 'invalid';
}
}
switch (order.status) {
case Status.open:
return 'open';
case Status.paid:
return order.isShipped ? 'on its way' : 'paid';
default:
return 'closed';
}
}

Its cyclomatic complexity is 9:

Branch point Adds
the function itself 1
if (order == null) 1
?? 1
the for loop 1
if (item.quantity <= 0 …) 1
|| 1
case Status.open 1
case Status.paid 1
the conditional expression … ? … : … 1
default 0

The limit rule is max_cyclomatic_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 15
strict 10

To change it, set the rule’s max (Configuring metrics):

assay:
rules:
max_cyclomatic_complexity:
max: 20

Where max_cognitive_complexity reports the same function, it takes this violation over, and the report marks the value taken over (Over the limit, suppressed, taken over).

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:

╭─ Cyclomatic complexity ──────────────────── limit 15 · 0 over · 5 functions ─╮
│ Value File Line Name │
│ ────────────────────────────────────────────────── │
│ 2 lib/prices.dart 2:5 total │
│ 2 lib/prices.dart 11:49 closure in cheapest │
│ 1 lib/prices.dart 11:5 cheapest │
│ 1 lib/prices.dart 14:8 name │
│ 1 lib/prices.dart 17:8 label │
╰──────────────────────────────────────────────────────────────────────────────╯
  • JSON: the key cyclomaticComplexity of each function, with its value, its limit and whether it is over it.
  • HTML: the column Cyclomatic of the table of functions.
  • Trend: the series Cyclomatic complexity over limit (Points and series).

Every form is on assay metrics.