Hello i have two samples of code
if/else if/else statements
private Object getObj(message) {
if (message.getA() != null)
return message.getA();
else if (message.getB() != null)
return message.getB();
else if (message.getC() != null)
return message.getC();
else return null;
}
Optional statements
private Optional<Object> wrap(Object o){
return Optional.ofNullable(o);
}
private Object getObj(message) {
return wrap(message.getA())
.orElseGet(() -> wrap(message.getB())
.orElseGet(() -> wrap(message.getC())
.orElse(null)));
}
So my question is how these two compare in terms of performance (i have about 15-20 if-else statements on actual code)?
Is it worth refactoring the code readability vs performance or is a misusage of optionals?
Also what is the performance penalty in case the if/else-if statements grown to 100+?
Thanks in advance
Java 8 has introduced a new class Optional in java. util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException .
How to change this if into Optional? It might be better to take advantage of method overloading in this case, so that the check() method with no parameter calls doMore(), while the check() method with the @NonNull String name only accepts non-null Strings. Otherwise, follow either Eugene's or luk2302's suggestions.
orElse(): returns the value if present, otherwise returns other. orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation.
As for your getters, don't use Optional. And try to design your classes so none of the members can possibly be null.
Don't use Optional
s for conditional logic.
They were designed, to be returned from a method to indicate a potentially absent value.
Just because you can nicely chain them into a single line doesn't mean that it's understandable. Also you literally gain nothing. The performance overhead may be significant. In the worst case N
objects being created and then discarded. Just stay with your "normal" if-else
chains.
Instead of finding ways to make your current code more readable, take a step back and ask yourself why you need 15-20 if-else statements. Can you split some logic up? Why do you need a getter for so many different fields with potentially different types in the first place? etc.
There is a third form (allowing still some variation).
return Stream.<Supplier<Object>>of(message::getA, message::getB, message::getC)
.map(Supplier::get)
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
Probably the least flexible and efficient at this moment, but clear.
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