Some years ago I wrote junit-parameters, which is basically a custom JUnit test runner that make it possible to add parameters to JUnit 4 test methods.

Browsing its source code SonarLint pointed me a large conditional if/else method from the ParameterTypeConverterFactory class:

This method converts the method parameter to its specific type based on its Class object. As it is few lines long, it showed me a good opportunity to refactor this code a little bit with a more elegant solution. This project has unit tests, so I could start refactoring it in small steps and start over again whether I have made a mistake.

I started by defining a functional interface called ParameterConverter:

and I created an immutable map which maps each Class object to its associated ParameterConverter instance (making use of method references):

Then I refactored the original conditional method to get the ParameterConverter instance from the convertersByClass map and mapping to an Optional instance in case it didn’t exist.

After those refactorings, SonarLint stopped warning me. Below is the modified version of the original method with some helper methods:

The complete code can be found at my GitHub here.

This was the first change of breaking this complicated conditional method into a more readable one. It was safe to do so because after each change I could run my unit tests suite to assert I haven’t broken anything. The next refactoring could be towards a more object-oriented approach like Replace Conditional with Polymorphism.

What did you think about this refactoring? Have you ever had such a situation? Drop your comments here!