Refactor this function to reduce its Cognitive Complexity from 40 to the 30 allowed

提交代码,报错:Refactor this function to reduce its Cognitive Complexity from 40 to the 30 allowed

降低认知复杂度sonar :Cognitive Complexity of functions should not be too high

1. 尽量减少打断线性代码执行的语句(如if else 、for、catch), 多层嵌套语句

2. 用三目运算符替代 if else. 如果没有else分支,不用再特意替换成三目运算符

3.多层嵌套的语句 拆出来,拆成方法

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To reduce the Cognitive Complexity of the method, we can try to simplify its logic and break it down into smaller, more manageable parts. Here are some suggestions: 1. Extract some of the code into separate methods with clear, descriptive names that explain what they do. This can help to make the overall logic of the method easier to understand. 2. Use early exits or guard clauses to reduce the number of nested blocks and simplify the overall flow of the method. 3. Consider using a switch statement or a lookup table to handle different cases or inputs, instead of using multiple if-else blocks. 4. Use meaningful variable names and comments to make the code more readable and understandable. Here is an example of how we could refactor a method to reduce its Cognitive Complexity: ``` public void doSomething(int input) { if (input < 0) { throw new IllegalArgumentException("Input must be non-negative"); } int result = 0; if (input == 0) { // Handle special case where input is zero result = 1; } else if (input == 1) { // Handle special case where input is one result = 1; } else { // Handle all other cases for (int i = 2; i <= input; i++) { result += i; } } System.out.println("Result: " + result); } ``` In this example, we have extracted the special cases into separate if-else blocks, and used an early exit to handle the non-negative input requirement. We have also used a meaningful variable name (`result`) to make the code more readable, and added a comment to explain the purpose of the method.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值