I prefer this early return writing style:
public static Type classify(int a, int b, int c) { if (!isTriangle(a, b, c)) { return Type.INVALID; } if (a == b && b == c) { return Type.EQUILATERAL; } if (b == c || a == b || c == a) { return Type.ISOSCELES; } return Type.SCALENE; }
Unfortunately, each return increases the cyclometric complexity metric calculated by Sonar. Consider this alternative:
public static Type classify(int a, int b, int c) { final Type result; if (!isTriangle(a, b, c)) { result = Type.INVALID; } else if (a == b && b == c) { result = Type.EQUILATERAL; } else if (b == c || a == b || c == a) { result = Type.ISOSCELES; } else { result = Type.SCALENE; } return result; }
The cyclomatic complexity of this latter approach, reported by Sonar, is lower than the first by 3. I was told that this could be the result of improper implementation of CC metrics. Or is Sonar right, and is that really better? These related questions do not seem to be consistent with this:
https://softwareengineering.stackexchange.com/questions/118703/where-did-the-notion-of-one-return-only-come-from
https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement
If I add support for a few more types of triangles, the return will add a significant difference in the metric and cause sonar disruption. I do not want to stick to the // NOSONAR method in the method, as this may mask other problems with new functions / errors added to this method in the future. Therefore, I use the second version, although I really do not like it. Is there a better way to handle the situation?
janos source share