I've recently seen a blog post (tweeted by @java) that suggests the following code is becoming increasingly common:
Optional.ofNullable(i).ifPresent(x -> doBlah(x));
instead of:
if (i != null) {
doBlah(i);
}
The use of Optional in this case appears very awkward to me, even ignoring the naming of the variables - the latter is easier to read and more idiomatic for the use case (handling nulls). I believe this also captures semantics better - i is likely from code that doesn't adhere to the semantics that Optional is trying to capture (as described in the possible duplicate and in this Oracle article).
I do not see one, but is there a good semantic cause to prefer the Optional.isNullable approach (ignoring the performance impact it may have depending on how it is used)?
It doesn't make much sense for the same unit of code to wrap a potentially null object in an Optional only to call ifPresent()
on it.
The more useful case is for an API that can return null objects to instead return an Optional. This forces the caller to handle potential null results in a null-safe way. Since the API and the caller are separate units of code, the extra work of wrapping an object in an Optional and forcing the caller to invoke ifPresent()
is not just busy-work but actually enforces a safer contract that protects against null-pointer exceptions.
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