I want to reduce cyclomatic complexity of my switch case my code is :
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;
}
}
This code blocks complexity is 16 and want to reduce it to 10. country, ccp, exchange and tenant are my diffrent objects. Based on type I will call their respective method.
If your first aim is only to reduce the cyclomatic complexity, you should create methods for each way of getting the name, like following.
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.
I believe it is a
Sonar
warning. I thinkSonar
warnings are not must-do-rules, but just guides. Your code block isREADABLE
andMAINTAINABLE
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:
Then we can just use the map to grab the right element
2nd approach:
All your objects have same method, so you can add an
Interface
withgetName()
method in it and change your method signature like:You can replace a switch/case statement with Dictionary>.
Take a look at the last example of this blogpost or this one
As per my knowledge, do not use return statement in switch statement. Apply that logic after the switch statement using a variable. Create a method for checking the null value and call that method from switch then you will able to reduce the Cyclomatic Complexity
I think you can lower the complexity just by making sure that something else is fixed in your code.
Take the case:
This implies that if the calender type is
COUNTRY
, the country the calender is associated with could benull
. 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 likewhich lowers your cyclomatic complexity to 5.
this worked for me