alternative to if statement in java
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);
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.
- Polymorphism, when behavior is dependent on the initial values
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;
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.