Why does the return statement increase complexity?

I use SonarQube for a Java project, but the calculation of complexity is not clear to me. The difficulty value is 3 for the following example:

public boolean even(int i) { if (i % 2 == 0) { return true; } return false; } 

According to the User Guide, complexity is calculated as follows: "This is cyclic complexity, also known as the McCabe metric. The function stream splits, the complexity counter increases by 1. Each function has a minimum complexity of 1." In the detailed description, it is mentioned that the return statement increases the value of complexity by one (if this is not the last statement in the method). I do not understand why the return statement breaks the control flow. In my opinion, there is only one possible way after each return statement in the control flow.

+3
source share
3 answers

Your example control flow graph contains 5 edges (E), 5 nodes (N) and one related component (P).

According to the definition of complexity (M = EN + 2P), the correct value for complexity is 2.

+3
source

This is not the control flow AFTER the return, but the fact that the control flow is divided between two points of exit from the method.

Consider these two methods:

 public boolean isAdult(int age) { boolean overEighteen = false; if (i > 18) { overEighteen = true; } return overEighteen; } 

and

 public boolean isAdultComplex(int age) { boolean overEighteen = false; // not used, but keeping methods identical if (i > 18) { return true; } return false; } 

If the calculation of cyclic complexity did not add one for an early return in the isAdultComplex method, these two methods would have identical cyclic complexity. But the second is certainly more complex, having two exit points.

These problems often seem trivial in such a short method, but imagine an early return in the 150-line method. It becomes much more difficult to mentally follow.

0
source

FYI guys, this discussion applies to https://jira.codehaus.org/browse/SONARJAVA-75 . I confirm that the complexity SonarQube reports is currently mixing Cyclomatic Complexity and Essential Complexity.

0
source

Source: https://habr.com/ru/post/1202577/


All Articles