I've read here why Optional.of()
should be used over Optional.ofNullable()
, but the answer didn't satisfy me at all, so I ask slightly different:
If you are SURE that your method does not return null
, why should you use Optional
at all? As far as I know, the more or less only purpose of it is to remind the "user of a method", that he might have to deal with null
-values. If he does not have to deal with null
-values, why should he be bothered with an Optional
?
I ask, because I recently made my service-layer return Optionals instead of nulls (in certain situations). I used Optional.of()
and was highly confused when it threw a NullPointer.
A sample of what I did:
Optional valueFromDB = getUserById("12");
User user = valueFromDB.get();
.....
public Optional<User> getUserById(String id) {
//...
return Optional.of(userRepository.findOne(id)); // NullPointerException!
}
If null is not possible, I don't see why one would wrap it in an Optional
. The dude in the linked answer said "well, if a NullPointer happens, it happens right away!" But do I really want that? If the sole purpose of an Optional
is, to remind the programmer who gets such an object, to keep null
in mind (he HAS to unwrap it), why should I want to have NullPointerException
at wrapping-time?
Edit: I needed to edit the question, because it got marked as duplicate, even though I already linked said question from the start. I also did explain, why the answer did not satisfy me, but now I need to edit my text with an explanation. But here is some appendix to what I want to ask, since I got 5 answers and everyone answers a different case, but none fully covered what I try to ask here:
Is there a reason, that Optional.of(null) is impossible and they specifically added Optional.ofNullable() for the null case?
Using streams should not be the problem with my idea of the implementation.
I got a lot of insight from your answers, thanks for that. But the real question has not been answered until now, as far as I can tell/read/understand.
Maybe I should have asked: "What if we remove the Optional.of()
method and only allow Optional.ofNullable()
in Java 9, would there be any problem except backwards-compatibility?"