java 圈复杂度

圈复杂度过大影响了程序的运行效率,应该保证每个方法的全复杂度空值在小于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 等判断运算

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值