我想降低我的开关盒的圈复杂度我的代码是:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!