How to refactor an application with multiple switch cases

design-patternsobject-oriented-design

I have an application which takes an integer as input and based on the input calls static methods of different classes. Every time a new number is added, we need to add another case and call a different static method of a different class. There are now 50 cases in the switch and every time I need to add another case, I shudder. Is there a better way to do this.

I did some thinking and came up with this idea. I use the strategy pattern. Instead of having a switch case, I have a map of strategy objects with the key being the input integer. Once the method is invoked, it will look up the object and call the generic method for the object. This way I can avoid using the switch case construct.

What do you think?

Best Answer

There are now 50 cases in the switch and every time I need to add another case, I shudder.

I love polymorphism. I love SOLID. I love pure object oriented programming. I hate to see these given a bad rep because they get applied dogmatically.

You have not made a good case for refactoring to strategy. The refactoring has a name by the way. It's called Replace Conditional with Polymorphism.

I've found some pertinent advice for you from c2.com:

It really only makes sense if the same or very similar conditional tests are repeated often. For simple, seldom-repeated tests, replacing a simple conditional with the verbosity of multiple class definitions, and likely moving all this far from the code that actually requires the conditionally required activity, would result in a textbook example of code obfuscation. Prefer clarity over dogmatic purity. -- DanMuller

You have a switch with 50 cases and your alternative is to produce 50 objects. Oh and 50 lines of object construction code. This is not progress. Why not? Because this refactoring does nothing to reduce the number from 50. You use this refactoring when you find you need to create another switch statement on the same input somewhere else. That's when this refactoring helps because it turns 100 back into 50.

So long as you're referring to "the switch" like it's the only one you have, I don't recommend this. The only advantage to come from refactoring now is that it reduces the chances that some goofball will copy and paste your 50 case switch.

What I do recommend is looking closely at these 50 cases for commonalities that can be factored out. I mean 50? Really? You sure you need that many cases? You might be trying to do to much here.

Related Topic