Search code examples
javajava-8option-typenullablenull-check

What is the difference between Optional.ofNullable() and `Optional.of()


First of all, I know the difference between the two methods.

  • Optional.of : Used to ensure that there is no null, if null is entered, nullPointExcepction

  • Optional.ofNullable : may or may not be null. Used to respond flexibly.

So, if I add orElseThrow(() -> new NullPointerException("null data")) to this, will it end up being the same?

I want to throw an error with explicit content.

So I get Optional.ofNullable(data).orElseThrow(() -> new NullPointerException("null data")))

use it as Is this pointless behaviour?

Optional.of(data).orElseThrow(() -> new NullPointerException("null data")))

I think this is also possible, but I'm just using ofNullable() to make the code look consistent.

to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?

then rather Is of.orElseThrow better?


Solution

  • to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?

    No. To see this, simply look at the types.

    public static <T> Optional<T> of(T value);
    
    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                                   throws X extends Throwable;
    

    Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout

    if (x == null) {
      throw new NullPointerException(...);
    }
    

    You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.

    Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.

    For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.

    If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?

    You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like

    public static <T> Optional<T> of(T value);
    public static <T> Optional<T> ofNullable(T? value);
    

    That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.

    It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.


    [1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.