Ugly case statements

So the other day I was going through some old C# code and encountered a giant wall of text in a function. What I mean is that I saw a giant switch-case statement that must have spanned a couple pages long. While the code works, it was ugly, disgusting, and every time I try to read it, my eyes would bleed a little bit.

I personally believe that your code should convey some sort elegance and that giant switch-case statement was anything but elegant. But what else can you do besides using a switch statement anyway?

Well the first option is to use a hashtable with a bunch of function pointers, so basically a dictionary of delegates in C#. This greatly reduces the amount of code needed to do the actual work. Of course, you might get a long initialize function to fill the dictionary somewhere else in the code, but most of the time that code will be smaller than your case statement regardless. And chances are, you only need to read the initialize code again if you ever need to add another action to the map anyways

Original Code:
switch (someEnum)
{
case Enum.SomeEnum1:
//do something
break;
case Enum.SomeEnum2:
//do something
break;
//Goes on for a very very long time
}

Option 1 (Delegates):
private Dictionary _actionMap = new { //Initialize here if you’re using .NET 3.5 or higher. Alternatively you can just call a method in your constructor }
Now in the actual function… all you have to do is something like
SomeDelegateType action = actionMap[someEnum];
action.DynamicInvoke(params);

Or if you need something more advanced, then perhaps another option is to use the command pattern.

Option 2 (Command Pattern):
ICommand command = SomeCommandFactory.CreateCommand(someEnum, params);
Command.Execute();

You can simply use a Dictionary of commands, but I’m just trying to show that there are always better ways to do it. I’m all for using design patterns (granted it has to make sense for the problem you’re trying to solve) because it increases readability and maintainability of the code. Often times, it makes your code more ‘elegant’.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *