Course contentsShow
← Software Engineering
Lesson 383 of 1,93311. Code Quality and ReadabilityFree lesson

Cyclomatic Complexity

Measuring complexity through the number of independent paths through code, typically driven by conditionals and loops.

Cyclomatic Complexity

What you'll learn: How to measure code complexity by counting the number of independent paths through your code.

What Is Cyclomatic Complexity?

Cyclomatic Complexity is a quantitative measure of how many different paths can be taken through your code. Every time you add a conditional (if, else, switch) or loop (for, while), you create additional paths and increase complexity.

Think of your code like a road map. A straight highway has just one path — simple and easy to follow. But a city with many intersections, traffic circles, and turn options? That's complex. Cyclomatic Complexity counts how many different routes exist from start to finish.

How It Works

The formula is straightforward:

  • Start with a baseline of 1 (the single straight-through path)
  • Add 1 for every if, else if, case in a switch, or loop
  • Add 1 for logical operators like && and || that create branching

Example:

function processOrder(order) {
    if (order.isPaid) {          // +1
        if (order.isShipped) {   // +1
            return "Complete";
        } else {
            return "Pending";
        }
    }
    return "Awaiting payment";
}
// Cyclomatic Complexity = 3

Why It Matters

Higher complexity means:

  • More paths to test (harder to achieve complete test coverage)
  • More mental load for developers reading the code
  • More places for bugs to hide

Functions with complexity above 10 are typically considered risky and candidates for refactoring using techniques like Extract Method or Replace Conditional with Polymorphism.

Key Takeaway: Cyclomatic Complexity quantifies how many decision points exist in your code—the more branches and loops, the higher the complexity and the harder the code is to understand, test, and maintain.