0

I know we have Optional.ofNullable() if the value can also be null. My question is, why isn't that the default behaviour for Optional.of() as well? If a value can not be null, why put in in the Optional in the first place? If it turns out to be null anyway, you will get an NPE all the same anyway. If you construct an Optional with the of() method, you will still have all the other methods of the Optional wrapper which only really have a purpose if the value can be null.

Edit: I have read Why use Optional.of over Optional.ofNullable? before posting this, but the answer there was "because you catch the error sooner, and it's easier to trace it that way". But I kinda disagree with that, maybe you will have a few extra lines in your stacktrace, but it's still easy to pinpoint the source of the NPE.

Zoltán Umlauf
  • 801
  • 1
  • 11
  • 30

2 Answers2

6

That method is meant to be used for non null parameters! The intent of that method is to guarantee that it will fail when called with null!

It is about the programmer communicating that intent to the reader!

When you don't know what is coming in, and that input might be null, then you tell that to the reader by using that other method. But when you know "an incoming null should never occur" then it might be fair to throw an exception when that very strict contract is violated.

GhostCat
  • 133,361
  • 24
  • 165
  • 234
  • Okay I think that's an okay reason, after all without using null, if the programmer calls a method on the null object, he/she might have just forgot the null check. That cant be said, when using Optional.of() – Zoltán Umlauf Apr 22 '19 at 19:07
  • 1
    Excellent point! I saw an NPE getting thrown in my log so I changed the code from .of() to .ofNullable() then read your answer and realized OH NO it might have been on purpose! But I looked at what is calling the method which returns this Optional and realized since we were doing isPresentOrElse this means we meant to use .ofNullable there. – LConrad May 21 '20 at 18:57
0

It can't be null. Optional.ofNullable(null) returns an Optional where isPresent is false, not one where it's true but with a null in it.