1

Sonar Lint rule "Methods should not be too complex" (squid:MethodCyclomaticComplexity) has an example of using more than one return statement in the program block. (see https://groups.google.com/forum/#!topic/sonarqube/BtvGoF6Tw7E for the cyclormatic complexity calculation rules)

The returns shortens the codes in a branch, and result with smaller code blocks. For example,


    int findBranchNumber(String input) {
        if ("branch1".equals(input)) {
            return 1;
        }
        if ("branch2".equals(input)) {
            return 2;
        }
        // ....
        return -1;
    }

The alternative will use a method variable (in this case) or bigger blocks. Whoever reads the code has to read the whole method before he/she realize only first 3 lines are relevant to the "branch1".

Please advise ...

1 Answers1

0

I'm personally do as you show in example. Only be careful if you allocate resources (for example file opening, memory allocation and so on) and need be freed it on return from function. In this case can be used trick with goto line hire described in first answer https://stackoverflow.com/a/245761

Community
  • 1
  • 1
komar
  • 861
  • 5
  • 8