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
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
