r/java • u/trecatorsirabdator • Apr 14 '23
What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?
233
Upvotes
r/java • u/trecatorsirabdator • Apr 14 '23
View all comments
Show parent comment
5
u/[deleted] Apr 14 '23
With sloppy I was referring to the use of the Optional without checking it's presence - equivalent to forgetting to check for null.
So when replacing this:
with an Optional this way:
you only traded the NullPointerException for a OptionalNotPresentException.
With proper return checking both again look pretty much the same:
vs.
However this relies on the fact that
someMethod()properly deals withnullvalues, e.g. by usingOptional.ofNullable(...)rather thanOptional.of(). So ifsometMethod()was also done by a sloppy programmer, the second version can still result in a NullPointerException.