Checkstyle and I agreed to get rid of the complicated if-clause. Due to the fact that I accidentaly broke another method during refactoring recently, I wanted to do a test-driven refactoring. To make things simple, there is a method in a utility class that is just right for this problem:
Obviously, this method can be used to simplify the code above. Maybe this is not a good example because the necessary change is obvious and easy. Nevertheless, it is a good exercise to practice some test-driven refactoring. So here is what I did, step by step.
1. Extract a method that only processes the logic
The first step of any of my refactorings is to isolate the code I want to refactor.
To guarantee that my refactoring doesn’t change the behavior of the code, I create a complete test-coverage in Line of Code (LOC) and of every logical path:
With that setting, all test are red because the logic has to be inverted (note the “!” before SomeUtilityClass.isEmpty):
3. Final Refactoring
Now all tests are green, so the final refactoring can be made:
The refactoring I made looks pretty complicated, considering such a tiny task. These baby-steps have two major advantages over a quick replace with the utility method. First, it is guaranteed to have the same logic. Second, the tests that have been written in the process of the refactoring will ensure the right behavior in the future if they are kept.