A Change to Switch Statements
posted on 2005-06-25 at 00:06:02 by Joel Ross
I ran into this today, and if it was available, my life would have been easier. Here's the problem I came up against.
Let's say that you have an object that has two properties: color and shape. You need to do something based on the combination of those two properties. Here's how you could do it now:
1: if(myObject.Shape == Shape.Round) {
2: if(myObject.Color == Color.Red) {
3: // Do something
4: } else if(myObject.Color == Color.Blue) {
5: // Do something
6: } else if(myObject.Color == Color.Green) {
7: // Do something
8: }
9: } else if (myObject.Shape == Shape.Square) {
10: if(myObject.Color == Color.Red) {
11: // Do something
12: } else if(myObject.Color == Color.Blue) {
13: // Do something
14: } else if(myObject.Color == Color.Green) {
15: // Do something
16: }
17: } else if (myObject.Shape == Shape.Triangle) {
18: if(myObject.Color == Color.Red) {
19: // Do something
20: } else if(myObject.Color == Color.Blue) {
21: // Do something
22: } else if(myObject.Color == Color.Green) {
23: // Do something
24: }
25: }
This could also be done with one level of if statements:
1: if(myObject.Shape == Shape.Round && myObject.Color == Color.Red) {
2: // Do something
3: }
And so on...
Either way, imagine now that switch statements could accept more than one expression. This makes this code much easier to read:
1: switch(myObject.Shape, myObject.Color){
2: case Shape.Round, Color.Red:
3: // Do something;
4: break;
5: case Shape.Round, Color.Blue:
6: // Do something;
7: break;
8: case Shape.Round, Color.Green:
9: // Do something;
10: break;
11: case Shape.Square, Color.Red:
12: // Do something;
13: break;
14: case Shape.Square, Color.Blue:
15: // Do something;
16: break;
17: case Shape.Square, Color.Green:
18: // Do something;
19: break;
20: case Shape.Triangle, Color.Red:
21: // Do something;
22: break;
23: case Shape.Triangle, Color.Blue:
24: // Do something;
25: break;
26: case Shape.Triangle, Color.Green:
27: // Do something;
28: break;
29: }
The code isn't that much smaller, but to me, it's much easier to read and see where things are happening. You could even go farther, and have a wildcard operator so you could say that a particular parameter doesn't matter for a particular case. For example, let's say that if the shape is a triangle, you need to do something if it's red, and something else if it's any other color. You could rewrite the last three case statements to be two case statements:
1: case Shape.Triangle, Color,Red:
2: // Do something
3: break;
4: case Shape.Triangle, *:
5: // Do something
6: break;
I haven't thought this completely through, so I may be missing something. I ran into a situation where I have 4 parameters to base off of, and this would have made the coding simpler and easier to understand.
Now, how do you go about getting a change into a language?
Categories: C#