Reduce Cyclomatic Complexity of Switch Statement - Sonar(降低 Switch 语句的圈复杂度 - Sonar)
问题描述
我想降低我的开关盒的圈复杂度我的代码是:
I want to reduce cyclomatic complexity of my switch case my code is :
public String getCalenderName() {
switch (type) {
case COUNTRY:
return country == null ? name : country.getName() + HOLIDAY_CALENDAR;
case CCP:
return ccp == null ? name : ccp.getName() + " CCP" + HOLIDAY_CALENDAR;
case EXCHANGE:
return exchange == null ? name : exchange.getName() + HOLIDAY_CALENDAR;
case TENANT:
return tenant == null ? name : tenant.getName() + HOLIDAY_CALENDAR;
default:
return name;
}
}
此代码块复杂度为 16,希望将其降低到 10.country、ccp、exchange 和tenant 是我的不同对象.根据类型,我将调用它们各自的方法.
This code blocks complexity is 16 and want to reduce it to 10. country, ccp, exchange and tenant are my diffrent objects. Based on type I will call their respective method.
推荐答案
我相信这是一个 Sonar
警告.我认为 Sonar
警告不是必须做的规则,而只是指南.您的代码块是 READABLE
和 MAINTAINABLE
原样.已经很简单了,如果你真的想改,可以试试下面这两种方法,看看复杂度会不会变低:
I believe it is a Sonar
warning. I think Sonar
warnings are not must-do-rules, but just guides. Your code block is READABLE
and MAINTAINABLE
as it is. It is already simple, but if you really want to change it you can try those two approaches below, and see if complexity becomes lower:
注意:我现在没有编译器,所以可能会出现错误,提前抱歉.
Note: I don't have compiler with me now so there can be errors, sorry about that in advance.
第一种方法:
Map<String, String> multipliers = new HashMap<String, Float>();
map.put("country", country);
map.put("exchange", exchange);
map.put("ccp", ccp);
map.put("tenant", tenant);
那么我们就可以使用地图来抓取正确的元素了
Then we can just use the map to grab the right element
return map.get(type) == null ? name : map.get(type).getName() + HOLIDAY_CALENDAR;
第二种方法:
你所有的对象都有相同的方法,所以你可以在其中添加一个带有 getName()
方法的 Interface
并更改你的方法签名,例如:
All your objects have same method, so you can add an Interface
with getName()
method in it and change your method signature like:
getCalendarName(YourInterface yourObject){
return yourObject == null ? name : yourObject.getName() + HOLIDAY_CALENDAR;
}
这篇关于降低 Switch 语句的圈复杂度 - Sonar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:降低 Switch 语句的圈复杂度 - Sonar
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01