liveBook · Manning

Cyclomatic complexity

As explained in Unit Testing Principles, Practices, and Patterns

Cyclomatic complexity is a metric that counts the independent control-flow paths or branching structure in a program or method.

Cyclomatic complexity measures a program or method by counting its branching points. It also represents the number of independent paths from entry to exit. section 7.1

1 + <number of branching points>

Calculate the metric as 1 plus the number of branching points. A method without control-flow statements therefore has complexity 1. section 7.1

Use the metric to reason about testing and refactoring:

  • Treat each simplest predicate as a branching point; an AND condition contributes two, producing complexity 3. section 7.1
  • Use independent paths as an indication of the tests needed for complete branch coverage. section 7.1
  • Prioritize complex, domain-significant code for unit testing because it offers stronger regression protection. section 7.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines the formula, independent-path interpretation, and compound-predicate counting, but does not develop a broader measurement system.
Examples
Uses a branch-free method and an AND condition to demonstrate complexity calculations.
What you can do after
Evaluate branching complexity and estimate the tests associated with complete branch coverage.
How it connects
Connects cyclomatic complexity with branch coverage, unit testing, domain significance, collaborators, and refactoring.

Also explained in

Compare how 5 books explain cyclomatic complexity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.