I have 10 cases in my switch statement. Each of them does the same thing with the other except that the assignments are different. If I have to change 1 line of code (during development) in one case block then I have to change all other 9 cases manually.
Here are the scenarios of each case statements:
- Each case contains long lines of code with many function calls and assignments.
- Only variable assignments, function arguments, and if statement conditions vary.
- There is no pattern/sequence in the assignment of variables and function arguments.
- Adding helper functions and calling them on each case statements is almost impossible for some reason.
How do I optimize or shorten this?
To illustrate:
final int CONSTANT_A = 0;
final int CONSTANT_B = 1;
...
final int CONSTANT_J = 10;
int varA = 0;
int varB = 1;
...
int varJ = 10;
int anothervarA = 0;
int anothervarB = 1;
...
int anothervarJ = 10;
int action = 0;
switch(something) {
case 1:
... long lines of code here
// If I have to change the variables below
// then I have to update all other variables in
// other cases below
varA = CONSTANT_J;
anothervarA = CONSTANT_B;
... another long lines of code here
int ret = someObject.foo(varA);
... do something with ret.
action = 5;
break;
case 2:
... long lines of code here
varB = CONSTANT_I;
anothervarB = CONSTANT_C
... another long lines of code here
int ret = someObject.foo(varA);
... do something with ret.
action = 100;
break;
...
...
case 9:
... long lines of code here
varI = CONSTANT_B;
anothervarI = CONSTANT_A;
... another long lines of code here
int ret = someObject.foo(varA);
... do something with ret.
action = 100;
break;
case 10:
... long lines of code here
varK = CONSTANT_A;
anothervarJ = CONSTANT_F;
... another long lines of code here
int ret = someObject.foo(varA);
... do something with ret.
action = 4;
break;
}
Nothing obvious jumps out, except maybe to factor all that code into a set of classes (or an enum), and rely on polymorphism instead of
switchto call the right one. So for instance, load your cases into aMap<Integer,Foo>— or even aList<Foo>if it’s not a sparse array — and then replace the switch withmyFoos.get(something).whatever();.As for assigning the variables when you’re done, if they’re member variables you could have the Foos set them directly; if this is always called in a single-threaded environment, you could have
foo.whatever()set up state and then have getters. If it’s in a multi-threaded environment, you could havewhatever()return back a new object with those getters. Something like: