降低切换语句的循环复杂度-Sonar

Ama*_*gar 6 java cyclomatic-complexity switch-statement sonarqube

我想减少开关情况的圈复杂度,我的代码是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码块的复杂度为16,并希望将其降低到10。country,ccp,exchange和tenant是我的不同对象。基于类型I将调用它们各自的方法。

hal*_*lil 9

我相信这是一个Sonar警告。我认为Sonar警告不是必须做的规则,而只是指南。您的代码块READABLE,并MAINTAINABLE因为它是。已经很简单了,但是如果你真的想改变它,你可以试试下面这两种方法,看看复杂度是否变低了:

注意:我现在没有编译器,所以可能会出现错误,提前抱歉。

第一种方法:

Map<String, String> multipliers = new HashMap<String, Float>();
    map.put("country", country);
    map.put("exchange", exchange);
    map.put("ccp", ccp);
    map.put("tenant", tenant);
Run Code Online (Sandbox Code Playgroud)

然后我们可以使用地图来抓取正确的元素

    return map.get(type) == null ? name : map.get(type).getName() + HOLIDAY_CALENDAR;
Run Code Online (Sandbox Code Playgroud)

方法二:

您所有的对象都具有相同的方法,因此您可以在其中添加一个InterfacewithgetName()方法并更改您的方法签名,例如:

getCalendarName(YourInterface yourObject){
    return yourObject == null ? name : yourObject.getName() + HOLIDAY_CALENDAR;
}
Run Code Online (Sandbox Code Playgroud)


may*_*wal 1

据我所知,不要在 switch 语句中使用 return 语句。使用变量在 switch 语句之后应用该逻辑。创建一个检查空值的方法并从 switch 调用该方法,然后您将能够降低循环复杂度