Skip to content

avoid_high_cyclomatic_complexity

v1.0.0WarningConfigurableCode Quality

This rule flags a function with more independent paths through it than the configured budget.

Cyclomatic complexity counts decisions: every branch, loop, catch, &&, ||, ?: and ?? adds one path a reader has to keep straight and a test has to cover. It measures something the line and statement budgets miss — twenty sequential statements are easy, while six nested conditions in five lines are not.

Three exclusions keep the rule pointed at real decisions, each of which came from running it against a production codebase:

  • An exhaustive switch over an enum or sealed type counts as one. The compiler proves every case is handled, so the cases are not paths the reader has to verify — counting them would report exactly the exhaustive pattern matching Dart 3 encourages.
  • operator == is never reported. It is one && per field by construction.
  • copyWith is never reported. It is one ?? per parameter.

The last two grow with the field count rather than with any decision, and neither can be split. A validating constructor, by contrast, still reports: its checks are genuine independent decisions.

This rule is in the pedantic preset: a budget is a house style, and the right number differs per codebase.

String describe(int n, bool flag, String? label) {
if (n < 0) return 'negative';
if (n == 0) return 'zero';
if (n > 100 && flag) return 'large and flagged';
if (n > 100 || flag) return 'large or flagged';
if (label != null && label.isNotEmpty) return label;
for (var i = 0; i < n; i++) {
if (i.isEven) print(i);
}
try {
return int.parse(label ?? '').toString();
} on FormatException {
return 'bad format';
}
}
String describe(int n, String? label) {
if (_isSpecialCase(n)) return _specialCase(n);
return label ?? 'unknown';
}
bool _isSpecialCase(int n) => n <= 0 || n > 100;
String _specialCase(int n) => n <= 0 ? 'small' : 'large';

This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:

many_lints.yaml
rules:
avoid_high_cyclomatic_complexity:
enabled: true
analysis_options.yaml
many_lints:
rules:
avoid_high_cyclomatic_complexity:
max_complexity: 10
count_exhaustive_switches: false
Option Type Default Description
max_complexity int 10 How many independent paths a function may have
count_exhaustive_switches bool false Whether each case of an exhaustive switch counts separately

To disable this rule:

many_lints.yaml
rules:
avoid_high_cyclomatic_complexity: false

To keep the rule on but skip certain paths, use per-rule exclude.