Function with cyclomatic complexity higher than thresholdRB-R1001
A function with 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 high cyclomatic complexity are more likely to have bugs and be harder to test. They may lead 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
def complex_function(a, b, c, d, e)
if a > 10
case b
when 1
if c == :foo
while d < 100
if e != :bar
case d % 3
when 0
puts "Case 0"
when 1
puts "Case 1"
else
puts "Case 2"
end
d += 1
end
end
else
puts "Option A"
end
when 2
if c == :baz
for i in 0..5
unless i == 3
puts "Loop iteration #{i}"
end
end
else
puts "Option B"
end
else
puts "Option C"
end
else
puts "Less than or equal to 10"
end
end
Recommended
def complex_function(a, b, c, d, e)
if a > 10
handle_case_b(a, b, c, d, e)
else
puts "Less than or equal to 10"
end
end
def handle_case_b(a, b, c, d, e)
case b
when 1
handle_case_1(c, d, e)
when 2
handle_case_2(c)
else
puts "Option C"
end
end
def handle_case_1(c, d, e)
if c == :foo
perform_while_loop(d, e)
else
puts "Option A"
end
end
def perform_while_loop(d, e)
while d < 100
unless e == :bar
handle_case_d_mod(d)
d += 1
end
end
end
def handle_case_d_mod(d)
case d % 3
when 0
puts "Case 0"
when 1
puts "Case 1"
else
puts "Case 2"
end
end
def handle_case_2(c)
if c == :baz
perform_for_loop
else
puts "Option B"
end
end
def perform_for_loop
(0..5).each do |i|
unless i == 3
puts "Loop iteration #{i}"
end
end
end
Issue configuration
Cyclomatic complexity threshold can be configured using the
cyclomatic_complexity_threshold
meta field 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 medium
(it's raised only for complexity greater than 15) for the Ruby 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. |