2

I've just moved from Java 7 to 8 and my code is littered with snippets like

if (myObj != null) {
    myObj.doSomething();
    myObj.doOtherThing();
}

I've noticed that null-checks are sometimes considered an anti-pattern and Java 8 promotes the use of Optional. Is there any benefit to having my code look like

Optional.ofNullable(myObj).ifPresent(obj -> {
    myObj.doSomething();
    myObj.doOtherThing();
});

Arguably, it makes the code harder to read.

Ares
  • 1,411
  • 1
  • 19
  • 35
  • related: http://stackoverflow.com/questions/271526/avoiding-null-statements –  Mar 17 '17 at 20:09
  • In many cases, null is a valid state for myObj, so it doesn't seem to be appropriate to use assertions. – Ares Mar 17 '17 at 20:12
  • 1
    The second snippet does not buy you anything. It replaces a simple if for a chain of calls and a lambda. Don't see the benefit – bichito Mar 17 '17 at 20:28
  • 3
    You are correct, in your example you should not use `Optional`. The linked question and its answers should give you an idea of when you should. – Ole V.V. Mar 17 '17 at 20:53

1 Answers1

3

One of the advantages of Optional is that when you return an Optional from a method, it indicates that a method can return null. When returning a usual object it's not obvious whether one shoud do the null check of the returned value.