Should Optional.ofNullable() be used for null check?

后端 未结 3 748
一向
一向 2020-12-19 04:33

Which null-check is preferable?

Optional.ofNullable(port).ifPresent(settings::setPort);

or

if (port != null) {
   settings.         


        
相关标签:
3条回答
  • 2020-12-19 05:17

    In Java, an Optional value is a fusion of a bit that indicates presence or absence, with a value of an arbitrary reference type T or a primitive int, long, or double.

    Fusing these is especially useful when returning a value from a method, as methods have only a single return value. It's often necessary to use a special value such as null in the case of reference types, or -1 in the case of int, as a sentinel to indicate the "no-value" case. Using Optional as a return value avoids the problem of the caller accidentally misusing the sentinel value as the real return value.

    Given this, line of code such as

    Optional.ofNullable(port).ifPresent(settings::setPort);
    

    is strange in that it fuses a value with the present/absent bit in the first part of the line and then immediately separates them in the second part of the line. This adds complexity to what is ultimately a fairly simple task: checking whether port is non-null and conditionally performing some action. The alternative code snippet:

    if (port != null) {
        settings.setPort(port);
    }
    

    expresses quite clearly exactly what it does.

    It's true that the if-statement takes more vertical space than the Optional chain. The Optional chain is denser, but it's also harder to understand: a poor tradeoff.

    0 讨论(0)
  • 2020-12-19 05:23

    It is dependent on several factors when to use this. If port is a property within the class, probably using Optional is a bit overkill. (and don't useOptionals as property as they are not serializbie)

    I think Optionals are great when for example writing a library.

    public Optional<Integer> getPort()
    

    Is much more descriptive for other developers then

    // Returns null if not set
    public Integer getPort()
    
    0 讨论(0)
  • 2020-12-19 05:34

    Although, the snippet you have posted in the question is just a simple way to avoid the ugly null-check, yet is valid, correct and null-safe. Follow your personal preference in this case.

    The real power of Optional are the following methods:

    • Optional::filter(Predicate<? super T> predicate) which applies a filter on a present value.
    • Optional::map(Function<? super T,? extends U> mapper) which applies a mapping function on a present value.

    As example, let's say you want to get another value from port to add to the list and avoid the NPE if port is null:

    Optional.ofNullable(port).map(port::getSomeValue).ifPresent(settings::setPort);
    

    Moreover, please, avoid the following meaningless substitution of null-check I see often:

    if (Optional.ofNullable(port).isPresent()) {
        settings.setPort(port);
    }
    
    0 讨论(0)
提交回复
热议问题