Alternative if in java

I am curious to see any alternative to regular if statements such as

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

so that you see all the if statements independently of each other, and no other condition. Please note that XYZ are completely different conditions, so the switch is not suitable.

+5
source share
11 answers

One of the “right object-oriented” answers would be to define an interface for the “rule” (using the condition () and action () methods), create 3 implementations, embed them in a collection, and then simply repeat through them in general form in:

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

, 300 /, 3.

Java8 , :

rules.parallelStream().filter(r -> r.condition()).forEach(r -> r.action());
+24

- .

, , evlation . .

  • ,
  • , , 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 ];
    
  • , , 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 ](); `
    
  • .

    :

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

    :

    b = thisCondition;

+7

if-else Java - switch (?:) , , ( if else). , , , .

+5

, , . , .

extract :

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

:

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

    // do 'a'
}
+3

.

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 , SomethingDoerFactory. , ifs.

:
http://misko.hevery.com/2008/12/08/clean-code-talks-inheritance-polymorphism-testing/

+2

, x, y, z a, b, c. , . .

0

if -.

, , . set if , < "" .

0

Switch ?

, .

0

. groovy - .

0

... myAnimator (, pos, | computeSpeed ​​());

=== undefined, ... .

0

All Articles