Adventures of a wannabe geek!

Ranting within

My Approach to Refactoring a Monster Switch Statement

I had to refactor some very old code a while back. The code looked similar to this:

I had to refactor it so that I could add more parts to it. There was no way I could add in more case statements so it all had to go. I took a cautious approach to the refactoring as it was pretty brittle and quite important code. The first step in refactoring made the code look as follows:

This mean that I could make sure that the function of the code didn’t change but that it was easier to read. This still couldn’t be unit tested though as there was no way to mock the behaviour of the case statements – it was all still in the same class. The next refactoring step was to allow some unit tests to be written. I was able to separate the behaviours into their own class and made the code look as follows:

This wasn’t enough for me. I still had this huge switch statement that was breaking the Open / Closed principle. This meant that in order to add more functionality to the switch, I had to change the switch and risk breaking it. This couldn’t happen. This made my final part of the code look as similar:

With this code I could make sure that I could write some unit tests around the behaviour of the class. This post only talks about going this far. I have since refactored the TaskRunner class much more as it was doing a lot more than 1 thing and thus breaking SRP. How would you have handled the same refactoring?