What is Cyclomatic Complexity?
What It Is And Two Examples Of Measuring It
Cyclomatic complexity is a software metric used to measure the complexity of a program or a specific piece of code. It is defined as the number of linearly independent paths through a program’s source code. In simpler terms, it represents the number of different execution paths a code can take based on the decision points (such as conditional statements or loops) within the code. A higher cyclomatic complexity indicates a more complex and potentially harder-to-understand code.
Cyclomatic complexity was introduced by Thomas J. McCabe in 1976 and is calculated using the formula:
Cyclomatic Complexity (CC) = Edges — Nodes + 2 * Connected Components
Where:
- Edges represent the number of connections between nodes (e.g., transitions between lines of code)
- Nodes are the distinct sections of code (e.g., individual lines or statements)
- Connected Components represent the number of separate pieces of code that are not connected to each other
Examples In Ruby
In the context of Ruby, let’s consider two examples to illustrate cyclomatic complexity:
Example 1:
def example_one(x)
if x > 10
puts "x is greater than 10"
else
puts "x is less than or equal to 10"
end
end
In this example, there is only one decision point (the if
statement), so the cyclomatic complexity is 2 (one path for the true branch and one path for the false branch).
Example 2:
def example_two(x, y)
if x > 10
puts "x is greater than 10"
elsif y > 20
puts "y is greater than 20"
else
puts "x is less than or equal to 10 and y is less than or equal to 20"
end
end
In this example, there are two decision points (the if
and elsif
statements), so the cyclomatic complexity is 3 (one path for each condition, plus one path for the else
branch).
Higher cyclomatic complexity values can indicate that a piece of code may be harder to understand, maintain, and test, so developers often aim to reduce complexity by refactoring code, breaking it into smaller, more manageable functions or methods.