hn.today

Cyclomatic Complexity in C#

blog.ndepend.com4 points0 comments
Screenshot of Cyclomatic Complexity in C#

Cyclomatic Complexity (CC) in C# measures the number of linearly independent execution paths through a method and is computed as 1 plus the number of decision points in the method’s control flow graph. Decision points include constructs like if, while, for, foreach, case/default labels, continue, goto, logical && and ||, catch, the ternary ?: and the null-coalescing ??; else, do, switch (the keyword itself), try, using, returns, object creation or simple method calls do not increment CC. CC equals the minimum number of tests needed to exercise every independent path, so higher scores indicate code that is harder to read, test and change. Common thresholds used by practitioners: 1-10 low risk, 11-20 moderate, 21-50 high risk, and >50 effectively untestable; Microsoft’s CA1502 flags >25 by default. Tools to measure and enforce CC in .NET include NDepend, Visual Studio’s Calculate Code Metrics, CA1502, Roslyn analyzers (e.g., SonarAnalyzer.CSharp), ReSharper and CodeRush.

A concrete example shows a single method with six ifs and one && scoring CC=8 and refactoring that method into several focused methods reduces per-method complexity while improving readability and testability; the total summed CC can rise but per-method reasoning is what matters. Practical reduction techniques include extract method, early returns/guard clauses, polymorphism, modern pattern matching and switch expressions, lookup tables and avoiding boolean flags. Pair CC with branch coverage and IL-level analysis for third‑party code, and use baseline-driven rules to focus remediation on new or growing complexity rather than overwhelming legacy refactors.

Read on blog.ndepend.com0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.