Short answer : yes, the usuage of Hashmap in your case does reduce Cyclomatic complexcity.
Detailed answer : Cyclomatic complexcity as per wikipedia is
It is a quantitative measure of the number of linearly independent paths through a program's source code.
There are various ways to tackle if-else cases. If-else statements makes the code less readable, difficult to understand. These if-else are also bad as each time you have addition / deletion / modification in the cases then you need to modify the existing code files where your other business logic remains same, and due to change in these files you need to test them all over again. This leads to maintainance issues as well as at all the places we need to make sure to handle the cases. Same issues exists with switch statements too, though they are little more readable.
The way you have used also reduces the different logical paths of execution.Another alternative approach is as below.
You can create an interface say IPair
. Let this interface define an abstract method public String getValue();
Lets define different classes for each case we have and let BlahMatch.java, Bling.java and Bong.java
implement IPair
and in the implementation of getValue()
method return the appropriate String
.
public String someMethod(IPair pair) {
return pair.getValue();
}
The advantage of above approach is, in case you have some new pair later you can still create a new class and pass the object of your new class easily, just you need to have your class provide implementation for IPair
.