2

It seems to me Optional adds little to code flow control and missing values handling. If a value behind an optional is not found, one still have to deal with absence of the value - then what's the point?

Compare:

Optional someMissingVal = codeThatReturnsOptional.getOptionalValue().orElse(null);
if( someMissingVal == null){
    throw(new NullPointerException());
} 
else return someMissingVal.get();

vs

Type someMissingVal = codeThatReturnsType.getTypeValue();
    if( someMissingVal == null){
        throw(new NullPointerException());
    } 
    else return someMissingVal;

So what's the big deal and how do I use Optional to harness its full power in the scenario above - as opposed to the "old style" missing value handling?

Nestor Milyaev
  • 4,784
  • 1
  • 31
  • 43
  • Good question. I'm not java-8-super-hacker, but seems some examples in net are wrong (in "old" style), especially when calling stack is deep – Jacek Cz May 10 '18 at 15:10
  • 1
    In your first example, `someMissingVal` is not of type `Optional`. Besides that, both examples are flawed. When you invoke a method that is documented to potentially return `null` (or an empty optional), there is no point in throwing a `NullPointerException` if it does. You are expected to *handle* the scenario. Besides that, enforcing a non-`null` value can be done much simpler: `return Objects.requireNonNull( codeThatReturnsType.getTypeValue());`. – Holger May 12 '18 at 09:55

2 Answers2

3

You can simplify your first snippet as following

return codeThatReturnsOptional.getOptionalValue()
                .orElseThrow(() -> new NullPointerException());

Does it simplify your code now? And it makes it readable too.

You can do a lot with Optional. This article from Oracle explains it.

azro
  • 47,041
  • 7
  • 30
  • 65
user7
  • 15,765
  • 4
  • 38
  • 68
3

You can do a null checks on the fly like:

public static void main(String[] args) {
    String s = null;
    String newS = Optional.ofNullable(s).orElse("default");
}

As well as throw exceptions:

public static void main(String[] args) {
    String s = null;
    String newS = Optional.ofNullable(s).orElseThrow(IllegalArgumentException::new);
}

Use some conditional statements:

public static void main(String[] args) {
    String s = "test";
    Optional.ofNullable(s).ifPresent(System.out::print);
}

Use it with Streams in more complicated scenarios.

J-Alex
  • 6,457
  • 10
  • 40
  • 58