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
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01