Is it a bad practice to have multiple returns? -
sonar lint rule "methods should not complex" (squid:methodcyclomaticcomplexity) has example of using more 1 return statement in program block. (see https://groups.google.com/forum/#!topic/sonarqube/btvgof6tw7e cyclormatic complexity calculation rules)
the returns shortens codes in branch, , result smaller code blocks. example,
int findbranchnumber(string input) { if ("branch1".equals(input)) { return 1; } if ("branch2".equals(input)) { return 2; } // .... return -1; }
the alternative use method variable (in case) or bigger blocks. whoever reads code has read whole method before he/she realize first 3 lines relevant "branch1".
please advise ...
i'm show in example. careful if allocate resources (for example file opening, memory allocation , on) , need freed on return function. in case can used trick goto line hire described in first answer https://stackoverflow.com/a/245761
Comments
Post a Comment