What Cyclomatic Complexity Is Too High? Thresholds, Examples, and Fixes (video)

Cyclomatic complexity counts the independent paths through a method. Learn how it is calculated, which thresholds teams use (10, 15, 20), and how to bring a complex C# method back down.

Read the full article

Transcript

What Cyclomatic Complexity Is Too High? Thresholds, Examples, and Fixes. Here's the short version.

Cyclomatic complexity is one of the oldest code metrics and still one of the most useful: it tells you how many independent paths run through a method, and therefore roughly how many test cases you need to cover it. The common question is where to draw the line.

How cyclomatic complexity is calculated. if and else if. for, foreach, while, and do loops. each case label in a switch. catch clauses.

Here's an example: Complexity = 1 + if + && + foreach + if + catch = 6.

So what number is too high?. 1–10: simple and easy to test — the usual target. 11–20: moderately complex — review it, and refactor if it keeps changing. 21–50: hard to understand and test — refactor before adding features. 50+: very high risk — effectively untestable as written.

How to reduce cyclomatic complexity. Use guard clauses to exit early instead of nesting conditions. Extract each branch of a large if-else or switch into a well-named method. Replace type or status switches with a dictionary or polymorphism. Move complex boolean conditions into named methods (IsEligibleForDiscount).

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos