eclipse中有metrics plugin通过计算决策(独立路径)来衡量cyclomatic complexity,具体来说:
(if, for, while, do, case, catch and the ?: ternary operator, as well as the && and || conditional logic operators in expressions)
例如,这里有一个得分为14的方法(每个决策路径1 +)
String getMonthName (int month) {
switch (month) {
case 0: return "January";
case 1: return "February";
case 2: return "March";
case 3: return "April";
case 4: return "May";
case 5: return "June";
case 6: return "July";
case 7: return "August";
case 8: return "September";
case 9: return "October";
case 10: return "November";
case 11: return "December";
default: throw new IllegalArgumentException();
}
}
我想知道在没有java中提到的分支的情况下是否有办法做出决定,这会破坏评估。基本上,我希望在没有插件检测它们的情况下做出不同的决定。指标显示出比实际情况更低的圈复杂度(独立路径/决策)。
答案 0 :(得分:2)
为了降低圈复杂度,您应该解耦代码或重构代码以实现更好的实现。
对于提供的示例,您可以使用数组:
static final String[] MONTHS = {"January", "February", ... };
static String getMonthName(int month) {
if (month < 0 || month >= MONTHS.length) {
throw new IllegalArgumentException(String.format("Month %d doesn't exist", month));
}
return MONTHS[month];
}
即使是上述方法也可以解耦:
static final String[] MONTHS = {"January", "February", ... };
static String getMonthName(int month) {
checkBoundaries(month, 0, MONTHS.length - 1, String.format("Month %d doesn't exist", month));
return MONTHS[month];
}
static void checkBoundaries(int n, int lowerBound, int upperBound, String errorMessage) {
if (n < lowerBound || n > upperBound) {
throw new IllegalArgumentException(errorMessage);
}
}