Well it might be a dumb question, bu开发者_如何学JAVAt I'm unable to find an answer:
The case is simple, I have a function with an integer in entry and two variable to assign depending of that. The problem is that the value assigned to the variables is common to certain case, but those case are not the same for the two variables. (if it's not clear enough, see the example).
I was wondering what was the best practice for such a case. Is it something like :
function test(a){
var x,y;
switch (a){
case 0:
case 1:
case 7:
y=...;
break;
case 2:
case 6:
y=...;
break;
case 3:
case 4:
case 5:
y=...;
}
switch(a){
case 5:
case 6:
case 7:
x=...;
break;
case 0:
case 4:
x=...;
break;
case 1:
case 2:
case 3:
x=...;
}
...
}
or
function test(a){
var x,y;
switch (a){
case 0:
x=...;
y=...;
break;
case 1:
x=...;
y=...;
break;
case 2:
x=...;
y=...;
break;
case 3:
x=...;
y=...;
break;
case 4:
x=...;
y=...;
break;
case 5:
x=...;
y=...;
break;
case 6:
x=...;
y=...;
break;
case 7:
x=...;
y=...;
}
...
}
Or to use a mix of the two with the value assigned to x in each case and to make groups for the value of y?
Note that there might be more than 8 value, it's just for the example. Thanks in advance.
If there's no real overlap between the different cases in the switch statements, you're probably better off having them separate.
If there was a majority of commonality between the actions, you could combine them with certain special cases within the individual case
blocks but you seem to indicate that's not the case here.
However, if this isn't just a simple example of a much more complex case, you can achieve a more compact solution with something like:
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12
static const int lookupX[] = { 2, 7, 1, 8, 2, 8, 1, 8, 2, 8, 4, 5, 9};
static const int lookupY[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9};
if ((a >=0) && (a < sizeof(lookupX) / sizeof(*lookupX)))
x = lookupX[a];
if ((a >=0) && (a < sizeof(lookupY) / sizeof(*lookupY)))
y = lookupY[a];
This will allow you to keep the values in a much smaller "configuration" section so that you can easily see the intent. The range checking and lookup then become very simple.
That code is tailored to C - I'm not sure what specific language you're using (because of the var
statement) but it's basically only doing the lookup if the index will be valid. You'll need to translate that bit to your language of choice.
精彩评论