Geeks With Blogs
Liam McLennan hackingon.net

This post is a message in a bottle. It cast it into the sea in the hope that it will one day return to me, stuffed to the cork with enlightenment. Yesterday I  tweeted,

what is the name of the pattern where you replace a multi-way conditional with an associative array?

I said ‘pattern’ but I meant ‘refactoring’. Anyway, no one replied so I will describe the refactoring here.

Programmers tend to think imperatively, which leads to code such as:

public int GetPopulation(string country)
{
   if (country == "Australia")
   {
       return 22360793;
   } else if (country == "China")
   {
       return 1324655000;
   } else if (country == "Switzerland")
   {
       return 7782900;
   }
   else
   {
       throw new Exception("What ain't no country I ever heard of. They speak English in what?");                    
   }
}

which is horrid. We can write a cleaner version, replacing the multi-way conditional with an associative array, treating the conditional as data:

public int GetPopulation(string country)
{
   if (!Populations.ContainsKey(country))
       throw new Exception("The population of " + country + " could not be found.");

   return Populations[country];
}

private Dictionary<string, int> Populations
{
   get
   {
       return new Dictionary<string, int>
           {
               {"Australia", 22360793},
               {"China", 1324655000},
               {"Switzerland", 7782900}
           };
   }
}

Does this refactoring already have a name? Otherwise, I propose

Replace multi-way conditional with associative array

Posted on Thursday, May 27, 2010 3:18 AM | Back to top

Copyright © Liam McLennan | Powered by: GeeksWithBlogs.net