Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional.ofNullable(i).ifPresent... vs if (i != null) [duplicate]

Tags:

java

optional

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)?

like image 951
James Fry Avatar asked Feb 16 '17 21:02

James Fry


1 Answers

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.

like image 103
Kylos Avatar answered Oct 08 '22 02:10

Kylos