I have code very similar to this example three times in a code behind.
Each time the switch is toggling off of an option that is sent to it. Each
time the code inside the case is exactly the same except for a parameter
based off of the case. Is using a switch/case and methods the best way
to do this? Should I think of using sometype of design pattern to avoid the repeative switch/case structure?
string option = dropDownList.SelectedValue.ToString();
switch (option.ToUpper())
{
case "ALPHA":
// do repeative code method here; only change is a parameter
break;
case "BRAVO":
// do repeative code method here; only change is a parameter
break;
case "CHARLIE":
// do repeative code method here; only change is a parameter
break;
case "DELTA":
// do repeative code method here; only change is a parameter
break;
default:
break;
}
Compilers are very good at optimizing switch/case constructs; the CLR will likely turn it into a lookup table or something similarly fast, so hand-rolling your own version such as Henk Holterman suggests is not what I would recommend. The CLR can do a better job than you can at choosing the best algorithm.
If it’s an issue of elegance or maintainability, and you have several switch/cases strewn about the same class performing similar functions, then one way to improve it is to encapsulate all of the functionality related to a single “case” into its own class instance, like so:
Then in your class/control/page:
After that you can start churning out events and other methods:
Of course, this is only a useful pattern if you have several of these switch/cases that you want to refactor into one. If you’ve only got one switch/case, you’re just going to end up with a lot more code this way, so leave it alone!
Other possibilities to improve maintainability include:
That’s about it. It’s simple to write, it’s easy to understand, it’s easy to maintain, it will save you time if you have a lot of switch/case constructs, and it still allows the CLR to perform the best possible optimizations. The only cost is the small amount of memory required to hold those readonly fields.