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
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
