Cyclomatic complexity

On this page 7

Cyclomatic complexity is a software metric that measures the number of linearly independent paths through a program’s control flow, giving a single integer that reflects how much branching logic a function or module contains. In software quality work it serves as an early indicator of testing effort, defect risk and maintainability.

The metric was introduced by Thomas McCabe in 1976 and is still reported by most static code analysis tools. It does not measure how hard code is to read in every sense, but it reliably flags functions whose decision structure has grown large enough to deserve review or refactoring.

How cyclomatic complexity is calculated

Cyclomatic complexity is calculated from the control flow graph of a program, in which nodes represent blocks of sequential statements and edges represent possible transfers of control. The classic formula is M = E – N + 2P, where E is the number of edges, N the number of nodes and P the number of connected components, usually one per function.

In practice, tools use a simpler equivalent: one plus the number of decision points. Each if, while, for, case label, catch clause and, in many tools, each short-circuit operator such as && or || adds one. A function with no branches therefore has a complexity of 1, the minimum possible value.

The table below shows how common constructs contribute to the count in typical tools.

ConstructAdded complexityNote
Straight-line code0Base value of 1 per function
if or else if+1 per conditionA plain else adds nothing
Loop (for, while)+1The loop condition is a decision
switch case label+1 per caseSome tools count the whole switch as one
Logical operator (&&, ||)+1 eachCounted in extended variants
catch block+1Exception paths are separate routes
Contribution of common constructs to the count

Because tools differ on operators, switch statements and ternary expressions, the same function can score differently in two analyzers. Teams should compare values only within one tool and configuration.

Interpreting cyclomatic complexity values

Cyclomatic complexity values are interpreted through threshold bands rather than as precise measurements. McCabe originally suggested a limit of 10 per module, and many organizations still use 10 to 15 as the point at which a function should be reviewed. Safety-critical standards and coding guidelines often apply stricter limits.

The following bands are widely used as a starting point; the exact cutoffs vary between teams and tools.

Complexity rangeTypical assessmentRecommended action
1 to 10Simple, low riskNo action needed
11 to 20Moderate complexityReview and consider splitting
21 to 50High complexity, high riskRefactor and add tests
Above 50Very high risk, hard to testRedesign the function
Commonly used risk bands per function

The value also sets a lower bound for branch testing: under McCabe’s basis path method, it equals the number of test cases needed to exercise a basis set of independent paths. A function with a score of 12 therefore needs at least 12 well-chosen tests for that coverage criterion, which makes the metric directly useful in test planning.

Cyclomatic complexity compared with other code metrics

Cyclomatic complexity captures structural branching, but it is only one dimension of code quality. Other metrics measure size, readability or coupling, and a balanced quality model combines several of them. The comparison below shows where each metric is strongest.

MetricWhat it measuresMain strengthMain weakness
Cyclomatic complexityIndependent control pathsLinks directly to test effortIgnores nesting and readability
Cognitive complexityMental effort to understand codePenalizes deep nestingNewer and less standardized
Lines of codeSize of a unitTrivial to computeSays little about logic
Halstead metricsOperators and operandsEstimates volume and effortAbstract and rarely intuitive
Maintainability indexComposite scoreSingle summary valueHides which factor is the problem
Cyclomatic complexity and related metrics

A key difference concerns nesting. Ten flat if statements and ten deeply nested ones produce the same cyclomatic score, yet the nested version is far harder to follow. Cognitive complexity was designed to address this gap, which is why many teams track both metrics side by side.

Using cyclomatic complexity in development practice

Cyclomatic complexity is most useful when it is measured automatically and continuously, typically in a continuous integration pipeline or a code review gate. Static code analysis tools report the value per function, highlight hotspots and can block a merge when a new function exceeds the agreed threshold.

  • Set a per-function limit, commonly 10 to 15, and apply it to new and changed code first.
  • Combine complexity with change frequency to find hotspots that are both complex and often modified.
  • Use the score to size test suites, especially for business rules and validation logic.
  • Allow documented exceptions for code such as parsers or state machines where a large switch is the clearest form.

When a function exceeds the limit, standard refactoring techniques reduce the count without changing behavior. The table below lists the most effective ones.

TechniqueHow it reduces complexityBest suited for
Extract methodMoves branches into smaller named functionsLong functions with distinct steps
Guard clausesReturns early instead of nesting conditionsInput validation logic
PolymorphismReplaces type checks with class behaviorRepeated switch on object type
Lookup tablesReplaces condition chains with dataMapping values to results
Simplify boolean logicMerges or removes redundant conditionsComplex compound conditions
Refactoring techniques that lower the score

Limitations and common misconceptions

The most common misconception is that low complexity means good code. A function can score 2 and still be badly named, poorly structured or wrong. The metric counts paths; it does not judge naming, data flow, coupling or correctness.

Another risk is gaming the metric. Splitting a function into many tiny fragments lowers each score while the total complexity of the module stays the same or grows, and readers must now jump between files. Thresholds should therefore guide human review, not replace it.

Finally, research links high complexity with higher defect density, but much of that correlation is explained by function size: longer functions contain more branches and more bugs. Cyclomatic complexity is best treated as one signal among several, alongside test coverage, code smells and the history recorded in the issue tracker.

Understanding it simply

Cyclomatic complexity counts how many different routes a piece of code can take from start to finish. Think of a road map: a straight road has one route, but every junction adds another way through. The more junctions, the more routes there are to check.

For programmers, more routes mean more testing and more places where mistakes can hide. A low number usually means the code is easy to test, while a high number is a warning sign that the code may need simplifying.

Applied in practice

A development team maintaining an online insurance quoting system adds a complexity check to its build pipeline with a limit of 15 per function. The first report shows that the premium calculation function scores 47, with nested conditions for age, region, vehicle type and discounts. It is also the function linked to the most bug reports in the previous year.

The team writes characterization tests, then applies guard clauses and lookup tables for regional rates and splits discount logic into separate functions. The largest remaining function scores 9. Over the next two releases, defects reported against pricing drop noticeably, and new discount rules take hours rather than days to add because each rule now lives in one small, testable function.