Function with cyclomatic complexity higher than thresholdCXX-R1000
A function with a high cyclomatic complexity can be hard to understand and maintain. Cyclomatic complexity is a software metric that measures the number of independent paths through a function. A higher cyclomatic complexity indicates that the function has more decision points and is more complex.
Functions with a high cyclomatic complexity are more likely to have bugs and be harder to test. They may also be more difficult to understand, leading to reduced code maintainability and increased development time.
To reduce the cyclomatic complexity of a function, you can:
- Break the function into smaller, more manageable functions.
- Refactor complex logic into separate functions or classes.
- Avoid multiple return paths and deeply nested control expressions.
Bad Practice
#include <cstdio>
void fizzbuzz(int x) { // cc = 2
if (x == 0 || x < 0) // cc = 4 (if, ||)
return;
for (int i = 1; i <= x; ++i) { // cc = 5 (for)
switch (i % 15) {
case 0: // cc = 6 (case)
std::printf("fizzbuzz\n");
break;
case 3:
case 6:
case 9:
case 12: // cc = 10 (case)
std::printf("fizz\n");
break;
case 5:
case 10: // cc = 12 (case)
std::printf("buzz\n");
break;
default:
std::printf("%d\n", x);
}
}
} // CC == 12; raises issues
int main() {
fizzbuzz(1000);
}
Recommended
#include <cstdio>
void fizzbuzz(int x) { // cc = 2
for (int i = 1; i <= x; ++i) { // cc = 3 (for)
int y = i % 3;
int z = i % 5;
if (y) std::printf("fizz"); // cc = 4 (if)
if (z) std::printf("buzz"); // cc = 5 (if)
if (!y && !z) std::printf("%d", i); // cc = 7 (if, &&)
std::printf("\n");
}
} // CC == 7
int main() {
fizzbuzz(1000);
}
Issue configuration
Cyclomatic complexity threshold can be configured using the
cyclomatic_complexity_threshold
(docs) in the
.deepsource.toml
config file.
Configuring this is optional. If you don't provide a value, the Analyzer will
raise issues for functions with complexity higher than the default threshold,
which is very-high
(only raise issues for >50) for the C & C++ Analyzer.
Here's the mapping of the risk category to the cyclomatic complexity score to help you configure this better:
Risk category | Cyclomatic complexity range | Recommended action |
---|---|---|
low | 1-5 | No action needed. |
medium | 6-15 | Review and monitor. |
high | 16-25 | Review and refactor. Recommended to add comments if the function is absolutely needed to be kept as it is. |
very-high. | 26-50 | Refactor to reduce the complexity. |
critical | >50 | Must refactor this. This can make the code untestable and very difficult to understand. |