Reduce Cyclomatic Complexity of Switch Statement - Sonar

前端 未结 7 1885
囚心锁ツ
囚心锁ツ 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:05

    If your objects: country, cpp, exchange and tenant share the same interface e.g. ObjectWithGetName you could refactor your code as following:

      public String getCalenderName() {
        ObjectWithGetNameMethod calendarType = null;
        switch (type) {
            case COUNTRY:
               calendarType = country;
               break;
            case CCP:
               calendarType = cpp;
               break;
            case EXCHANGE:
               calendarType = exchange;
               break;
            case TENANT:
               calendarType = tenant;
               break;
            default:
               calendarType = null;
        }
        return (calendarType != null ? (calendarType.getName() + HOLIDAY_CALENDAR) : name);
      }
    

    Also I think it will be nice to move switch to separate method since it looks like something witch will be used in many different places.

提交回复
热议问题