Refactor Large Switch Statement Blocks with Actions

Update - Based on some feedback, I should add that this isn’t suitable for all scenarios (team-based project may require more consistent paradigms), but I think it’s a viable option for other use cases (e.g. one-person team, small project, prototyping etc..). Also, ICommand is just an example for my use-case but unrelated to the principle. I just came across this post on Stackoverflow which shows how it could be further extended for filtering and this post showing a refactor using a similar technique with the dictionary. 

I sometimes have large switch statements in my TellDJ code and these can not only look ugly, but they can be annoying to maintain. I figured I’d refactor my code and decided to come up with a new alternative that took advantage of Actions so that it felt cleaner and more maintainable.

In my case, as I’m using MVVM, I receive commands from the View via commands to my ViewModel. However instead of exposing lots of ICommand properties, I chose to expose a couple and grouped them together.

For example, Playback controls would share one ICommand property and Navigation controls would be have its own one, so there would be two distinct ICommand properties that will handle multiple buttons from the View.

Naturally, a switch statement would make sense here.

The problem was that the switch statement would grow larger and for Views with many buttons, this would become ugly. I could group a few more ICommands but even that would result in large blocks of code. Therefore, I decided to create an alternative to the switch statement in the form of a dictionary.

As you can see from the code, a Dictionary<string, Action> is created and filled with the relevant methods. And instead of a large switch statement, we simply call


This makes it much easier to add and remove methods that handle the commands. Of course, this isn’t worth doing if the switch statement is small but I think it’s quite a good alternative for larger ones.

As always, any feedback welcome but I thought I’d share this for anyone looking to refactor large switch statements.