Reduce Cyclomatic Complexity of Switch Statement - Sonar

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

    I think you can lower the complexity just by making sure that something else is fixed in your code.

    Take the case:

    case COUNTRY:
      return country == null ? name : country.getName() + HOLIDAY_CALENDAR;
    

    This implies that if the calender type is COUNTRY, the country the calender is associated with could be null. This is something you should prevent by design because I can't see a reason why this could be a valid situation. Why would you have a country calender without a country?

    So make sure that there is a non-null object associated with the calender as soon as you assign a type to it. In this way your cases will be like

    case COUNTRY:
      return country.getName() + HOLIDAY_CALENDAR;
    

    which lowers your cyclomatic complexity to 5.

提交回复
热议问题