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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With