圈复杂度过大影响了程序的运行效率,应该保证每个方法的全复杂度空值在小于5的范围。
本例子纯属为了测试每个函数的全复杂度为多大。
public class MaxComplexity {
public static void main(String[] args) {
int score = 90;
complexityIfElse(score);
complexitySwitch(score);
}
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
private static void printArray2(int[] array) {
for (int value : array) {
System.out.println(value + " ");
}
System.out.println();
}
private static void ifValue(int value) {
if (value == 90) {
System.out.println("score 等于 90");
} else {
System.out.println("score 不等于 90");
}
}
private static void isValue(int value) {
int flag = value == 90 ? 1 : 0;
System.out.println(flag);
}
/**
* if - else if -else 的最大圈复杂度测试
* 本函数的圈复杂度为8,
* @param score
*/
private static void complexityIfElse(int score) {
if (score < 60) {
System.out.println("分数低于60分,不及格");
} else if (score < 70) {
System.out.println("分数在[60,70)之间,及格,良");
} else if (score < 80 && score >= 70) {
System.out.println("分数在[70,80)之间,良");
} else if (score < 90 && score >= 80) {
System.out.println("分数在[80,90),优秀");
} else {
System.out.println("分数在[90, 100]之间,非常优秀");
}
}
/**
* switch 的最大圈复杂度测试
* 此函数的圈复杂度为6.
* @param score
*/
private static void complexitySwitch(int score) {
switch (score) {
case (60):
System.out.println("分数低于60分,不及格");
break;
case (70):
System.out.println("分数在[60,70)之间,及格,良");
break;
case (80):
System.out.println("分数在[70,80)之间,良");
break;
case (90):
System.out.println("分数在[80,90),优秀");
break;
default:
System.out.println("分数在[90, 100]之间,非常优秀");
}
}
}
圈复杂度降低方法:
①抽取方法:将一段可以组织在一起实现简单功能的代码抽取为方法,独立出来。将可以并列的条件应用map替代。
②将多个条件分支中都会执行的代码提取出来最后执行。
③将简单的条件判断转换为三元预算符(if-else --> ? :)。
④提炼逻辑与算法,想一个新的算法。
⑤将多个类似条件判断为一个方法,根据不同参数判断返回结果。例子:多处string非空判断。
⑥尽量少用switch case , && , || , if 等判断运算。