I couldn't find a way to do the following with Java's Optional:
if (SOME_OBJECT != null) {
doSomething(SOME_OBJECT);
} else {
doSomethingElse();
}
By using Optional
, I don't mean mean replacing SOME_OBJECT == null
with Optional.ofNullable(SOME_OBJECT).isPresent()
, which a much longer syntax than simply checking if null.
What I would expect is something like:
Optional.ofNullable(SOME_OBJECT)
.ifPresent(this::doSomething)
.orElse(this::doSomethingElse);
I couldn't find an API like the one I just wrote. Does it exist? If so, what is it? If not, why not? :)
The second piece of code looks like an anti-pattern :( Why? Perhaps Java's architects prevented this syntax on purpose...
ifPresent
doesn't return theOptional
, and that there doesn't seem to be anifAbsent
.ifPresent
andorElse
must re-check the result ofofNullable
. It seems at least as complicated as an if-then to read and would be somewhat harder to maintain. All downside (even if small), no upside.Optional
as a whole. :-) But I haven't used it in anger (I haven't done any serious Java in years now), so my opinion there is reactionary and uninformed... :-)Optional
was introduced as part of the streaming implementation. It's used under the hood in streams to preventNullPointerException
s. From that point of view I think it makes sense -- as part of a larger cohesive framework. Randomly sprinkling your code withOptional
probably isn't going to have a cohesive effect on its design or implementation, you'd need some good reason to use these sorts of objects.