Question

I use SonarQube for a Java project but the complexity calculation is not clear for me. The complexity 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 the complexity is calculated as follows: “It is the cyclomatic complexity, also known as McCabe metric. Whenever the control flow of a function splits, the complexity counter gets incremented by one. Each function has a minimum complexity of 1.” In the detailed description it is mentioned that the return statement increases the complexity value by one (if it is not the last statement in the method). I do not understand why the return statement splits the control flow. In my opinion, there is only one possible way after every return statement in the control flow.

Was it helpful?

Solution

The control-flow graph of your example contains 5 edges (E), 5 nodes(N) and one connected components (P).

According to the defintion of the complexity (M=E-N+2P) the correct complexity value is 2.

OTHER TIPS

It's not the control flow AFTER the return but the fact that control flow has split between two method exit points.

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 cyclic complexity calculation did not add one for the early return in the isAdultComplex method, these two methods would have identical cyclic complexity. But the second is definitely more complex by having two exit points.

This issues often seem trivial in a short method like this, but imagine an early return in a 150 line method. It becomes much harder to mentally follow.

FYI Guys, this discussion relates to https://jira.codehaus.org/browse/SONARJAVA-75. I do confirm that for the time being, the complexity reported by SonarQube mixes the "Cyclomatic Complexity" and the "Essential Complexity".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top