Reduce Cyclomatic Complexity of Switch Statement - Sonar

前端 未结 7 1915
囚心锁ツ
囚心锁ツ 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 22:56

    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.

    First approach:

    Map multipliers = new HashMap();
        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;
    

    2nd approach:

    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;
    }
    

提交回复
热议问题