java中if语句的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1621445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:54:55  来源:igfitidea点击:

alternative to if statement in java

javaif-statement

提问by Hellnar

I am curious to see any alternative(s) to the regular if statements such as

我很想看到常规 if 语句的任何替代方案,例如

if(x)
     do a;
if(y)
     do b;
if(z)
    do c;

so as you see all if statements are seperate and no else condition. Please notice that X Y Z are totally seperate conditions so switch wouldn't fit.

所以你看到所有的 if 语句都是独立的,没有 else 条件。请注意,XYZ 是完全独立的条件,因此开关不适合。

采纳答案by Alex R

One "truely object oriented" answer would be to define an interface for "Rule" (with condition() and action() methods), create 3 implementations, stuff them into a collection, and then just iterate through them generically as in:

一个“真正面向对象”的答案是为“规则”定义一个接口(使用 condition() 和 action() 方法),创建 3 个实现,将它们填充到一个集合中,然后一般地遍历它们,如下所示:

List<Rule> rules = .... ; // your 3 rules initialized here somehow
for(Rule r : rules) {
  if(r.condition()) {
    r.action();
  }
}

This makes a lot more sense if you have 300 rules/conditions rather than just 3.

如果您有 300 个规则/条件而不是 3 个,这会更有意义。

In Java8, you may want to do this instead, if the rules are CPU-intensive:

在 Java8 中,如果规则是 CPU 密集型的,您可能想要这样做:

rules.parallelStream().filter(Rule::condition).forEach(Rule::action);

回答by dfa

this is the most simple, readable yet effectivesolution. I would be surprised to see effective alternatives here.

这是最简单、易读但有效的解决方案。如果在这里看到有效的替代方案,我会感到惊讶。

EDIT

编辑

you can try to apply extract methodseveral times:

您可以尝试多次应用提取方法

doAIfX();
doBIfY();
doCifZ();

where methods are defined by:

其中方法定义为:

void doAIfX() {
    if (!X) {
        return;
    }

    // do 'a'
}

回答by Nat

it really depends on what x, y, z and a, b, c are. Sometimes if statements are more suitable. Sometimes polymorphism is more suitable.

这实际上取决于 x、y、z 和 a、b、c 是什么。有时 if 语句更合适。有时多态更合适。

回答by Bill the Lizard

The alternatives to if-elsein Java are the switch statement and the conditional ternary(?:) operator, neither of which do exactly what you're asking (handle just an ifwith no else). The code you posted is the best way to do it, in my opinion.

if-elseJava 中的替代方法是 switch 语句和条件三元( ?:) 运算符,它们都不能完全满足您的要求(仅处理if带 no 的操作else)。在我看来,您发布的代码是最好的方法。

回答by artemb

Use polymorphism.

使用多态。

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();
     }
}

The if is not completely eliminated, but it is moved to SomethingDoerFactory. This solution is not applicable in all cases, but in some of them it is a very good alternative to multiple ifs.

if 并没有完全消除,而是移到了SomethingDoerFactory。此解决方案并非适用于所有情况,但在其中一些情况下,它是多个 if 的非常好的替代方案。

Here is a nice talk about it:
http://misko.hevery.com/2008/12/08/clean-code-talks-inheritance-polymorphism-testing/

这是一个很好的讨论:http:
//misko.hevery.com/2008/12/08/clean-code-talks-inheritance-polymorphism-testing/

回答by Bill Bingham

The short answer is yes.

简短的回答是肯定的。

There are a few time you can avoid using if for conditional evluation and branching all together. And they have moments of appropriateness.

有几次您可以避免将 if 用于条件评估和分支。他们有合适的时刻。

  1. Polymorphism, when behavior is dependent on the initial values
  2. 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 ];
    
  3. 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 ](); `
    
  4. Direct boolean assignment.

    We hate:

    if (thisCondition == true) {  
      b = true;  
    } else {  
      b = false;  
    }
    

    Should be:

    b = thisCondition;

  1. 多态性,当行为依赖于初始值时
  2. 参考赋值,当您知道可能的初始值并且它们与返回值具有 1 比 1 的相关性时。列表在这方面比数组更好,但是......

    // 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 ];
    
  3. 引用分支,当您知道可能的初始值并且它们与要使用的函数/分支具有 1 比 1 的相关性时。(示例不是 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 ](); `
    
  4. 直接布尔赋值。

    我们恨:

    if (thisCondition == true) {  
      b = true;  
    } else {  
      b = false;  
    }
    

    应该:

    b = 这个条件;

回答by Zac Thompson

You will need to have these if statements somewhere.

您将需要在某处使用这些 if 语句。

They can be refactored into other methods to keep the present method clean, as others have suggested. If you need to re-use this same setof if statements in a number of places, it mightbe possible use the Decorator Pattern.

正如其他人所建议的那样,它们可以重构为其他方法以保持当前方法的清洁。如果您需要重新使用相同的设置,如果在一些地方的语句,它可能可以使用装饰模式

回答by fastcodejava

It sounds like a perfect case for using closure. But for that you need groovyor something similar.

这听起来像是使用closure的完美案例。但为此你需要groovy或类似的东西。

回答by MistereeDevlord

How about... myAnimator(thing, pos, speed | computeSpeed());

怎么样... myAnimator(thing, pos, speed | computeSpeed());

if speed === undefinedit will then computeSpeed... I think.

如果速度 ===未定义,那么它会计算速度...我想。

回答by HoaPhan

It's really depends on the context... but yeah if-else is only one of control flowstatement in java: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html

这真的取决于上下文......但是if-else只是Java中的控制流语句之一:https: //docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html