CyclomaticComplexity - shibotsu/obs-clone GitHub Wiki

Cyclomatic Complexity

Cyclomatic complexity is a metric developed by Thomas McCabe in 1976 to quantify the complexity of a program's control flow.

How It Works

It is calculated by analyzing the control flow graph of a function or method. The nodes represent code blocks, and the edges represent control paths (e.g., if, while, for, case, etc.).

The formula is: M = E - N + 2P

  • M = Cyclomatic complexity
  • E = Number of edges
  • N = Number of nodes
  • P = Number of connected components (typically 1 for a single function)

What it describes

  • M = 1: Straight-line code (no conditionals or branches)
  • M between 2–10: Simple, manageable code
  • M > 10: Complex, potentially harder to test and maintain
  • M > 20: Very complex and likely needs refactoring

Why It Matters

High cyclomatic complexity can:

  • Increase the risk of bugs
  • Make unit testing more difficult
  • Indicate that the function is doing too much

Best Practices

  • Break down functions with high complexity into smaller ones
  • Use guard clauses to reduce nesting
  • Aim to keep complexity below 10 where possible

Possible paths

These are the possible paths for the following code snippet:

  • P,1,2,3,K
  • P,1,2,5,6,2,3,K
  • P,1,2,5,7,8,2,3,K
  • P,1,2,5,7,9,2,3,K
  • P,1,2,5,7,9,10,2,3,K

code_20250602_215058_via_10015_io2222

← Back to Home