Cyclomatic complexity is a software metric that measures the number of linearly independent paths through your source code. In simpler terms, it quantifies the complexity of your program’s control flow. Every decision point (such as if
, elif
, for
, while
, and except
in Python, or if
, for
, while
, case
, and catch
in JavaScript) increases the number of possible execution paths. The base complexity is always 1, and each decision point adds 1 to this base number.
Why does it matter? A lower complexity value (e.g., 1–5) generally indicates that a function is simple, easy to understand, and maintainable. As complexity increases, so does the likelihood of bugs and the effort needed for testing and maintenance.
Here’s what the different complexity scores typically indicate:
How is it calculated? The tool starts with a base complexity of 1 and then adds 1 for every decision point found in the code. For example:
Example (Python):
def compare(a, b): if a > b: return a elif a < b: return b else: return 0
In this example, there are two decision points (if
and elif
). The cyclomatic complexity is therefore calculated as 1 (base) + 2 = 3.
Use this tool to quickly assess the complexity of a code snippet. A higher complexity value indicates a greater number of potential execution paths, which can make your code harder to test and maintain. Conversely, a lower value suggests simpler and more manageable code. Monitoring cyclomatic complexity can guide you in refactoring and simplifying critical parts of your codebase, leading to improved overall maintainability and reliability.