Reduce Cyclomatic Complexity of Switch Statement - Sonar

前端 未结 7 1928
囚心锁ツ
囚心锁ツ 2021-01-17 22:50

I want to reduce cyclomatic complexity of my switch case my code is :

public String getCalenderName() {
        switch (type) {
    case COUNTRY:
        r         


        
7条回答
  •  忘掉有多难
    2021-01-17 23:14

    If your first aim is only to reduce the cyclomatic complexity, you should create methods for each way of getting the name, like following.

     public String getCalenderName() {
        switch (type) {
        case COUNTRY:
            return getCountryName();
        case CCP:
            return getCcpName();
        case EXCHANGE:
            return getExchangeName();
        case TENANT:
            return getTenantName();
        default:
            return name;
        }
    }
    
    private String getCountryName() {
        return country == null ? name : country.getName() + HOLIDAY_CALENDAR;
    }
    
    private String getCcpName() {
        return ccp == null ? name : ccp.getName() + " CCP" + HOLIDAY_CALENDAR;
    }
    
    private String getExchangeName() {
        return exchange == null ? name : getName.toString() + HOLIDAY_CALENDAR;
    }
    
    private String getTenantName() {
        return tenant == null ? name : getName.toString() + HOLIDAY_CALENDAR;
    }
    

    Note in your specific example, I suppose that you have 1 class that gather (at least) 4 quite similar behaviours. A refactoring would certainly make more sense, in order to have for example one base implementation (abstract or not), and 4 other inherited classes.

提交回复
热议问题