Programming  /  C# November 23, 2009

Invoking methods based on a parameter without if-else statements in C#

Simplify conditional code using the "delegate dictionary" pattern.

Today I found myself writing this piece of code:

switch (searchType)
{
    case SearchType.Bananas:
        SearchForBananas();
        break;
    case SearchType.Oranges:
        SearchForOranges();
        break;
    case SearchType.Kiwis:
        SearchForKiwis();
        break;
    default:
        SearchForBananas();
        SearchForOranges();
        SearchForKiwis();
}

Except for me not being very found of switch statements this code might look OK at first glance, but it has one serious flaw. What happens if I, or someone else, have to add another search method? Or remove one of the methods? We have to make changes in two places. First we have to add another case and then we have to add one more method call to the default case. In my opinion that severely reduces the flexibility (or agility if you will) of the code and increases the risk of bugs being introduced when changes are made, especially when there are a lot more actions than three.

Still, I often find myself writing code similar to this and while I know there are at least one better solution, an action map, or the “delegate dictionary” pattern if you will, I keep forgetting how to do it. Hopefully blogging about the problem will fix that :-)

Anyway, using a delegate dictionary the code can be refactored to:

Dictionary<SearchType, Action> actionMap = new Dictionary<SearchType, Action>();

actionMap.Add(SearchType.Bananas, SearchForBananas);
actionMap.Add(SearchType.Oranges, SearchForOranges);
actionMap.Add(SearchType.Kiwis, SearchForKiwis);

if(actionMap.ContainsKey(searchType))
    actionMap[searchType]();
else
    foreach (Action action in actionMap.Values)
        action();

While the amount of code is only slightly reduced with this approach it makes the code much more flexible as adding or removing actions only requires the code to be changed in a single place. And when there’s 15 possible actions instead of three it also looks a hell of a lot prettier.

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

More about C#