我很想看看除了常规的if语句之外的其他选择,例如
if(x)
do a;
if(y)
do b;
if(z)
do c;
如您所见,所有的if条件语句都是独立的,没有else条件。请注意,X、Y、Z是完全独立的条件,因此switch语句不适用。
我很想看看除了常规的if语句之外的其他选择,例如
if(x)
do a;
if(y)
do b;
if(z)
do c;
如您所见,所有的if条件语句都是独立的,没有else条件。请注意,X、Y、Z是完全独立的条件,因此switch语句不适用。
一个真正面向对象的方法是为 "Rule" 定义一个接口(包括 condition() 和 action() 方法),创建 3 个实现类,将它们放入集合中,然后像这样通用地迭代它们:
List<Rule> rules = .... ; //在此处初始化你的 3 条规则 for(Rule r : rules) { if(r.condition()) { r.action(); } }
如果你有 300 条规则/条件,那么这种方法就更为合理。
在 Java8 中,如果规则具有 CPU 密集性,则可以使用以下方法:
rules.parallelStream().filter(Rule::condition).forEach(Rule::action);
Referrenced Assignment, when you know the possible initial values and they have 1 to 1 correlation with the return values. Lists are better than arrays for this, but...
// Example: if (a==1) { b=2; } if (a==2) { b=17; } // Becomes int fx(2); // our array of answers fx[0] = 2; fx[1] = 17; b = fx[ a - 1 ];
Referrenced Branching, when you know the possible initial values and they have 1 to 1 correlation with the function/branch to use. (example not Java)
// Example:
if (a==1) { doSomething1(); }
if (a==2) { doSomething2(); }
// Becomes
function * fx(2); // our array or better still, list of functions
fx[0] = &doSomething1;
fx[1] = &doSomething2;
`fx[ a - 1 ](); `
Direct boolean assignment.
We hate:
if (thisCondition == true) {
b = true;
} else {
b = false;
}
Should be:
b = thisCondition;
if-else
的方法有switch语句和条件三目运算符(?:),但它们都不能完全满足您的需求(仅处理没有else
的if
)。在我看来,您发布的代码是最好的方法。请注意保留HTML标记。使用多态性。
interface SomethingDoer {
public void doSomething();
}
class ADoer implements SomethingDoer { ... }
class BDoer implements SomethingDoer { ... }
class CDoer implements SomethingDoer { ... }
public class Main {
public static void main (String[] args) {
SomethingDoer doer = new SomethingDoerFactory(args).getDoer();
doer.doSomething();
}
}
if(x) do a;
。 - Bill the Lizard这是最简单、易读且有效的解决方案。如果有其他有效的替代方案,我会感到惊讶。
编辑
您可以尝试多次应用“提取方法”:
doAIfX();
doBIfY();
doCifZ();
方法的定义方式如下:
void doAIfX() {
if (!X) {
return;
}
// do 'a'
}
可以像这样做,根据条件实现枚举并调用覆盖方法。
public enum Rule{
a(){
@Override
public void do(){
// do something.
}
},
b(){
@Override
public void do(){
// do something.
}
},
c(){
@Override
public void do(){
// do something.
}
public abstract void do();
}
}
public class Test{
public static void main(String[] args){
Rule r = Rule.valueOf("a");
r.do();
}
}
如何使用以下代码...
myAnimator(thing, pos, speed | computeSpeed());
如果speed === undefined,则会计算速度...我想是这样的。
这真的取决于 x、y、z 和 a、b、c 是什么。有时候 if 语句更合适,有时候多态更合适。
你需要在某个地方使用这些 if 语句。
它们可以重构到其他方法中,以保持当前方法的清晰度,正如其他人所建议的那样。如果你需要在多个地方重复使用这个集合的 if 语句,可能可以使用装饰器模式。
这似乎是使用闭包的完美案例。但是为此,您需要使用Groovy或类似的东西。
if
语句是有害的。 - Alex R