Cyclomatic Complexity in Software Testing with Example

โšก Smart Summary

Cyclomatic Complexity is a software metric developed by Thomas McCabe in 1976 that counts the independent paths through a program. It is calculated from a control flow graph and gives the number of test cases required for full branch coverage.

  • ๐Ÿ“ Two Formulas: V(G) = E – N + 2 from the graph, or V(G) = P + 1 from the count of decision points.
  • ๐Ÿงฎ Direct Meaning: The value equals the maximum number of independent paths, and therefore the test cases needed.
  • ๐Ÿ—บ๏ธ Graph Basis: Nodes represent processing steps and edges represent the flow of control between them.
  • ๐ŸŸข 1 to 10: Structured, well-written code with high testability and low maintenance cost.
  • ๐ŸŸ  21 to 40: Very complex code with low testability, where refactoring usually costs less than testing.
  • ๐Ÿ› ๏ธ Tooling: SonarQube, Visual Studio Code Metrics, Radon, and Lizard compute it automatically.

Cyclomatic Complexity in Software Testing

What is McCabeโ€™s Cyclomatic Complexity?

Cyclomatic Complexity in Software Testing is a testing metric used for measuring the complexity of a software program. It is a quantitative measure of independent paths in the source code of a software program. Cyclomatic complexity can be calculated by using control flow graphs or with respect to functions, modules, methods or classes within a software program.

Independent path is defined as a path that has at least one edge which has not been traversed before in any other paths.

This metric was developed by Thomas J. McCabe in 1976 and it is based on a control flow representation of the program. Control flow depicts a program as a graph which consists of Nodes and Edges.

In the graph, Nodes represent processing tasks while edges represent control flow between the nodes.

McCabeโ€™s Cyclomatic Complexity

Flow Graph Notation for a Program

Flow Graph notation for a program defines several nodes connected through the edges. Below are Flow diagrams for statements like if-else, While, until and normal sequence of flow.

Flow graph notation for a program

How to Calculate Cyclomatic Complexity

Mathematical representation:

Mathematically, it is set of independent paths through the graph diagram. The Code complexity of the program can be defined using the formula –

V(G) = E - N + 2

Where,

E – Number of edges

N – Number of Nodes

V (G) = P + 1

Where P = Number of predicate nodes (node that contains condition)

Example –

i = 0;
n=4; //N-Number of nodes present in the graph

while (i<n-1) do
j = i + 1;

while (j<n) do

if A[i]<A[j] then
swap(A[i], A[j]);

end do;
j=j+1;

end do;

Flow graph for this program will be

Calculate Cyclomatic Complexity

Computing mathematically,

  • V(G) = 9 – 7 + 2 = 4
  • V(G) = 3 + 1 = 4 (Condition nodes are 1,2 and 3 nodes)

Basis set, the four independent execution paths:

  • 1, 7
  • 1, 2, 6, 1, 7
  • 1, 2, 3, 4, 5, 2, 6, 1, 7
  • 1, 2, 3, 5, 2, 6, 1, 7

Properties of Cyclomatic Complexity

Following are the properties of Cyclomatic complexity:

  1. V (G) is the maximum number of independent paths in the graph
  2. V (G) >=1
  3. G will have one path if V (G) = 1
  4. A commonly used guideline is to keep V(G) at 10 or below for a single module

How This Metric is Useful for Software Testing

Basis Path testing is one of White box technique and it guarantees to execute at least one statement during testing. It checks each linearly independent path through the program, which means the number of test cases needed equals the cyclomatic complexity of the program.

This metric is useful because of properties of Cyclomatic complexity (M) –

  1. M can be number of test cases to achieve branch coverage (Upper Bound)
  2. M can be number of paths through the graphs. (Lower Bound)

Consider this example –

If (Condition 1)
Statement 1

Else
Statement 2

If (Condition 2)
Statement 3

Else
Statement 4

Cyclomatic Complexity for this program will be 8-7+2=3.

As complexity has calculated as 3, three test cases are necessary to the complete path coverage for the above example.

Steps to be followed

The following steps should be followed for computing Cyclomatic complexity and test cases design.

Step 1 – Construction of graph with nodes and edges from the code

Step 2 – Identification of independent paths

Step 3 – Cyclomatic Complexity Calculation

Step 4 – Design of Test Cases

Once the basic set is formed, TEST CASES should be written to execute all the paths.

More on V (G)

Cyclomatic complexity can be calculated manually if the program is small. Automated tools need to be used if the program is very complex as this involves more flow graphs. Based on complexity number, team can conclude on the actions that need to be taken for measure.

The following table gives an overview of the complexity number and the corresponding meaning of v (G):

Complexity Number Meaning
1 to 10

Structured and well-written code

High testability

Cost and effort is less

11 to 20

Complex code

Medium testability

Cost and effort is medium

21 to 40

Very complex code

Low testability

Cost and effort are high

>40

Not at all testable

Very high cost and effort

Tools for Calculating Cyclomatic Complexity

Many tools are available for determining the complexity of the application. Some complexity calculation tools are used for specific technologies. Complexity can be found by the number of decision points in a program. The decision points are if, for, for-each, while, do, catch, case statements in a source code.

Examples of tools are

  • OCLint – Static code analyzer for C and Related Languages
  • SonarQube – Reports cyclomatic and cognitive complexity across more than 25 languages
  • Visual Studio Code Metrics – Built-in cyclomatic complexity analysis for .NET assemblies
  • Radon and Lizard – Command-line complexity analysers for Python and for multi-language projects respectively
  • GMetrics – Find metrics in Java related applications

Uses of Cyclomatic Complexity

Cyclomatic Complexity can prove to be very helpful in

  • Helps developers and testers to determine independent path executions
  • Developers can assure that all the paths have been tested at least once
  • Helps us to focus more on the uncovered paths
  • Improve code coverage in Software Engineering
  • Evaluate the risk associated with the application or program
  • Using these metrics early in the cycle reduces more risk of the program

How to Reduce Cyclomatic Complexity

A high complexity number is a signal, not a verdict. Four refactorings account for most of the reduction achievable in practice.

  • Extract method. Moving a branch into its own function splits the complexity between two modules. The total across the system is unchanged, but each unit becomes independently testable.
  • Replace a conditional chain with a lookup. A long if-else-if ladder testing the same variable becomes a map or a switch, which collapses many decision points into one.
  • Use guard clauses. Returning early on invalid input removes the nesting that a single large if-else block creates, without changing behaviour.
  • Replace conditionals with polymorphism. Where a conditional switches on a type, moving each branch into its own class removes the decision entirely.

Before, with V(G) = 4:

if (user != null) {
    if (user.isActive()) {
        if (user.hasRole("admin")) {
            return grantAccess();
        }
    }
}
return denyAccess();

After, with the same behaviour and the nesting removed:

if (user == null) return denyAccess();
if (!user.isActive()) return denyAccess();
if (!user.hasRole("admin")) return denyAccess();
return grantAccess();

A caution about the metric. Cyclomatic complexity counts decisions, not difficulty. A switch statement with twenty simple cases scores 21 yet is easy to read, while a deeply nested block scoring 8 may be far harder to understand. Use the number to find candidates for review, not as a target to be gamed.

FAQs

Ten or below per module is the common guideline. Between 11 and 20 the code is complex but manageable. Above 20 testability falls sharply, and above 40 the module is generally considered untestable as written.

Both give the same result. P + 1 is faster for hand calculation because you only count decision points. E – N + 2 is what tools use, since they already build the control flow graph.

Not necessarily. Cyclomatic complexity counts decisions rather than difficulty, so a flat switch with twenty simple cases scores highly while remaining easy to read. Treat the number as a prompt for review.

They combine it with change frequency and defect history to rank which modules carry the most risk, directing review and test effort to the code most likely to fail.

Yes. AI assistants propose guard clauses, extracted methods, and lookup tables that reduce the count. Verify behaviour with the existing test suite, because a refactoring that changes logic defeats the purpose.

Summarize this post with: