Understanding the cyclomatic complexity calculator — concept and principle
Cyclomatic complexity, introduced by Thomas McCabe, counts the independent paths through a piece of code. It is used to judge how hard a function is to test and maintain. This calculator finds it either from the control-flow graph's edges, nodes and components or from the number of binary decisions, and compares the result with McCabe's suggested limit of 10.
How it is calculated
From the graph: M = E − N + 2P
From decisions: M = number of binary decisions + 1
- E edges (possible jumps between blocks), N nodes (blocks of code), P connected components (separate routines analysed together).
- M is also the number of test paths in a basis set.
- Decision points = M − P.
The principle
Draw the code as a graph: straight-line blocks are nodes and possible transfers of control are edges. A routine with no branches is a single path, M = 1. Each two-way decision such as an if or a loop condition adds one more independent path, which is why decisions + 1 gives the same value. The graph formula comes from graph theory: E − N + 2P counts the independent cycles once the exit is connected back to the entry. In structured testing, M is the minimum number of test cases needed to exercise every independent path at least once.
Worked example
Default inputs: E = 12 edges, N = 10 nodes, P = 1 routine.
- M = 12 − 10 + 2 × 1 = 4.
- Basis paths to test = 4.
- Decision points = 4 − 1 = 3 binary decisions.
- 4 is at most 10, so the result is within the limit.
How to read the result
McCabe proposed keeping each module at 10 or below; the NIST structured-testing report discusses this limit and notes that some organisations allow somewhat higher values with justification. A function above the limit is a candidate for splitting into smaller functions. Low complexity does not guarantee good code, and high complexity is sometimes acceptable for simple switch-like dispatch, but the number is a useful flag for review.
Common mistakes
- Counting a multi-way switch as one decision; each case adds a path.
- Forgetting compound conditions; "a && b" can count as two decisions in strict counting.
- Treating M as a direct measure of code quality.
- Mixing up nodes (blocks) and individual statements.
Frequently asked questions
What is a good cyclomatic complexity?
McCabe suggested 10 or less per function; lower is generally easier to test.
How does it relate to testing?
M is the minimum number of test paths needed for basis-path coverage.
Does a loop add complexity?
Yes, the loop condition is a decision and adds one path.
Can complexity be reduced?
Splitting functions, removing duplicated conditions and using lookup tables often help.
Sources: A. H. Watson and T. J. McCabe, "Structured Testing: A Testing Methodology Using the Cyclomatic Complexity Metric", NIST Special Publication 500-235 (1996)