Question

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

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.

Was it helpful?

Solution

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:

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.

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

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

OTHER TIPS

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.

  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;

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

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.

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

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

EDIT

you can try to apply extract method several times:

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

where methods are defined by:

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

    // do 'a'
}

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

You will need to have these if statements somewhere.

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 set of if statements in a number of places, it might be possible use the Decorator Pattern.

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

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

if speed === undefined it will then computeSpeed... I think.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top