Hasty Briefsbeta

Bilingual

Cyclomatic Complexity in C#

2 days ago
  • Cyclomatic Complexity (CC) counts independent execution paths through a method, computed as 1 + number of branching constructs (if, while, for, case, &&, ||, ?:, ??).
  • A score of 1 is simplest, 10 is traditional upper bound, 25+ is flagged as excessive by Microsoft's CA1502 analyzer.
  • CC provides minimum number of test cases needed for full path coverage; higher scores mean harder to read, test, and change.
  • Refactoring involves extracting methods, using guard clauses, polymorphism, switch expressions, lookup tables, and eliminating boolean parameters.
  • Thresholds: 1-10 low risk, 11-20 moderate, 21-50 complex, >50 untestable; but context matters (parsers, serializers often higher).
  • Tools like NDepend, Visual Studio Code Metrics, and Roslyn analyzers measure CC; baseline-driven rules are better for legacy code.
  • Pair CC with branch coverage (CRAP score) for risk assessment; IL CC can evaluate third-party libraries.
  • Cognitive Complexity differs by factoring nesting depth and boolean operators; both metrics are complementary.