Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to if statement in java

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.

like image 912
Hellnar Avatar asked Oct 25 '09 17:10

Hellnar


1 Answers

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);
like image 109
Alex R Avatar answered Sep 28 '22 13:09

Alex R