Sonar cyclomatic complexity rule issue - discourages multiple return statements

gopalsaob picture gopalsaob · May 22, 2014 · Viewed 12.4k times · Source

For the following piece of code, sonarqube computes the method cyclomatic complexity as 9

String foo() {
    if (cond1) return a;
    if (cond2) return b;
    if (cond3) return c;
    if (cond4) return d;
    return e;
}

I understand as per the rules for computation http://docs.sonarqube.org/display/SONAR/Metrics+-+Complexity the complexity of 9 is correct. So complexity of the method is = 4 (if) + 4 (return) + 1 (method) = 9

This complexity can be reduced, if I have a single exit point.

String foo() {
    String temp;
    if (cond1) { 
        temp = a;
    } else if (cond2) {
        temp = b;
    } else if (cond3) { 
        temp = c;
    } else if (cond4) {
        temp = d;
    } else {
        temp = e;
    }
    return temp;
}

I believe this code is more cluttered and unreadable than the previous version and I feel having methods with return on guard conditions is a better programming practice. So is there a good reason why return statement is considered for computation of cyclomatic complexity? Can the logic for computation be changed so that it doesn't promote single exit point.

Answer

Peter Lawrey picture Peter Lawrey · May 22, 2014

I agree you should use some common sense and go with the code which you believe is simplest.

BTW You can simplify you code and have just one return if you use ? :

String foo() {
    return cond1 ? a :
           cond2 ? b :
           cond3 ? c :
           cond4 ? d : e;
}