我的 switch 语句中有 10 个案例。他们每个人都做同样的事情,只是任务不同。如果我必须在一个 case block 中更改 1 行代码(在开发期间),那么我必须手动更改所有其他 9 个 case。
以下是每个案例陈述的场景:
- 每个案例都包含很长的代码行,其中包含许多函数调用和赋值。
- 仅变量赋值、函数参数和 if 语句条件有所不同。
- 变量和函数参数的分配没有模式/顺序。
- 出于某种原因,添加辅助函数并在每个 case 语句上调用它们几乎是不可能的。
如何优化或缩短它?
举例说明:
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;
}
最佳答案
没有什么明显的跳出,除了可能将所有代码分解到一组类(或枚举)中,并依赖多态性而不是switch
调用正确的人。例如,将您的案例加载到 Map<Integer,Foo>
-- 甚至是List<Foo>
如果它不是稀疏数组 - 然后将开关替换为 myFoos.get(something).whatever();
.
至于完成后分配变量,如果它们是成员变量,则可以让 Foos 直接设置它们;如果始终在单线程环境中调用它,则可以有 foo.whatever()
设置状态,然后获取 setter/getter 。如果是在多线程环境中,则可以有 whatever()
使用这些 setter/getter 返回一个新对象。像这样的东西:
FooResult result = myFoos().get(something).getResult(whatever, args);
varA = result.getA();
action = result.getAction();
etc
关于java - 缩短 switch block 内 case 语句中的代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222601/