Reputation: 4711
I have a SELECT/SWITCH statement that has continued to grow... I THINK I should be about done.
However, there are currently 19 options... is there something that would be better than this?
Coding in C#
IE:
switch (Request["typeOfRequest"].ToString())
{
case "comboFills":
Response.ContentType = "text";
Response.Write(getVizData());
break;
case "linkFormField":
Response.ContentType = "text";
Response.Write(getVizRuleFields());
break;
case "getDispositions":
Upvotes: 0
Views: 2063
Reputation: 63471
Switch statements can be way larger than that... However, eventually you may run into efficiency concerns. I don't think that 19 cases is a problem. I've had much larger statements. Usually a switch statement is not a processing bottleneck, so it's the last thing you optimize.
Each case translates onto the CPU as a test and a jump, so think of how many operations your worst case would be and decide whether it's worth fussing over, and how many operations you would actually save (both worst case and average).
Saying that, there's a couple of obvious options. If you have numeric types and they are evenly distributed, you can split your switch statement into multiple switches....
if value < 50
switch
...
end
else if value < 100
switch
...
end
else
...
end
This is of course trickier to maintain, and may rely upon knowledge of constant values that makes your code ugly. It's really just a grungey search tree...
Another way is to put all your cases into functions, and build a tree or hash table that maps each value to a function handler. That way you can always rely on O(logN) search times (or better, in the case of hash tables). I repeat: don't do this unless you have a very good reason to.
Hope that helps give you some insight. Apologies for not being language-specific. You didn't mention a language, but I'm assuming it's something like BASIC.
Upvotes: 2