Why use Optional.of over Optional.ofNullable?

后端 未结 4 1258
悲哀的现实
悲哀的现实 2020-11-28 01:20

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = ;
         


        
相关标签:
4条回答
  • 2020-11-28 01:44

    Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

    0 讨论(0)
  • 2020-11-28 01:51

    Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

    0 讨论(0)
  • 2020-11-28 01:55

    In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

    String nullName = null;
    String name = Optional.ofNullable(nullName).orElseThrow(NullPointerException::new);
    
    0 讨论(0)
  • 2020-11-28 02:04

    This depends upon scenarios.

    Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

    Then, in that case, you can use Optional<?>.

    String nullName = null;
    
    String name = Optional.ofNullable(nullName)
                          .map(<doSomething>)
                          .orElse("Default value in case of null");
    
    0 讨论(0)
提交回复
热议问题