Unnamed Refactoring

Posted by Liam McLennan on Geeks with Blogs See other posts from Geeks with Blogs or by Liam McLennan
Published on Thu, 27 May 2010 02:18:50 GMT Indexed on 2010/05/27 8:33 UTC
Read the original article Hit count: 238

Filed under:

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

© Geeks with Blogs or respective owner