1

I did look at the following question How to refactor this huge switch statement?

I am refactoring a code which has a huge switch statement in the Page_Load event handler of an aspx page.

The code is something like this

string switchValue = GetSwitchValue();     

switch(switchValue) 
{   
 case "switchValue1" : 
       stopwatch.Restart();
       HandlerForSwitchValue1();
       stopwatch.Stop();
       LogDetails();
       break;
 case "Foo" : 
       stopwatch.Restart();
       HandlerForFoo();
       stopwatch.Stop();
       LogDetails();
       break;
 ... 
 ... 
 ...
 }

I plan to create another class say 'Handlers' which would contain a Dictionary of string and the Action delegate.

IDictionary<string, Action> actionMaps = new Dictionary<string, Action>();

my question is, where do I populate the dictionary? If I populate it in the 'Handlers' class, how do I access the Private handler methods defined in the aspx code behind?

The other option is to populate the Dictionary in the code behind. something like this

Handlers.Add("SwitchValue1", HandlerForSwitchValue1);

The Add method or whatever I name it would add the items to the dictionary in the 'Handler's class.

Now I will have 100 lines which would look something like this. Again what do I get out of this?

Handlers.Add("SwitchValue2", HandlerForSwitchValue2);
Community
  • 1
  • 1
AlwaysAProgrammer
  • 2,821
  • 2
  • 29
  • 40
  • Note, that the compiler creates such a mapping for you. The C# compiler has special handing for switch statements operating on strings. It creates a dictionary under the covers. – usr Apr 21 '14 at 21:58

1 Answers1

3

Unless the mapping changes at runtime, you can create a static readonly Dictionary as a field of a class and initialize that field from the constructor of that class.

If you want the mapping to be dynamic at runtime, you can instead use a static property in a class. The backing store for that property could also be initialized in the class constructor.

Eric J.
  • 139,555
  • 58
  • 313
  • 529
  • @Eric.. The mappings are static. So you are advising me to create the Dictionary in the other class. But how do I access the private handlers defined in the code behind? Please advise if I understand your suggestion correctly. – AlwaysAProgrammer Apr 21 '14 at 21:41
  • @Yogendra: It has been a while since I worked with aspx, but you should be able to add the static field/property to the code behind file. – Eric J. Apr 21 '14 at 21:49