Domanda

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);
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top