0

Java has an Optional type, which alleviates a lot of the pain null causes. Is there any valid use cases for null anymore? Why would one use null but not Optional?

One possible venue is perhaps performance. null probably is faster than an Optional.

kolistivra
  • 4,229
  • 9
  • 45
  • 58
  • 4
    Part of the problem is that an `Optional` can itself be null – Justin Apr 06 '17 at 18:12
  • 1
    [Optional is intended for return types only.](http://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555) It should never be used for property types or argument types. – VGR Apr 06 '17 at 18:15
  • 1
    "which alleviates a lot of the pain null causes" [citation needed] – Boann Apr 06 '17 at 18:21
  • 1
    Performance is irrelevant. You can use `null` anywhere you want. `Optional` for return values has an advantage for chained operations such as you use with streams. – Lew Bloch Apr 06 '17 at 18:25
  • Related: [Why should Java 8's Optional not be used in arguments](http://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments). [Should I use Java8/Guava Optional for every method that may return null?](http://stackoverflow.com/questions/18681243/should-i-use-java8-guava-optional-for-every-method-that-may-return-null). – Ole V.V. Apr 07 '17 at 08:58

1 Answers1

3

Optional object's typical use case is for method's return types only.

Also, it is NOT a good practice to use Optional as method arguments or constructor arguments because we can't enforce non-null optional objects i.e., the Optional object itself can be null. In other words, even if you pass an Optional object as method parameter as we can't guarantee that the Optional object itself is NOT null, you might still end up with a null check. I suggest you can look here on a detailed discussion on this subject.

The other point is that Java's Optional is NOT Serializable, so you can't use Optional on the variables/fields whichever require Serialization. You can refer more on this here.

So, the important point is that we still need null references wherever Optional does not make sense.

Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67
  • They argue that rather than accepting an `Optional` argument, for the convenience of the caller you should overload your method: one version requires a non-null argument and one doesn’t have that parameter at all. – Ole V.V. Apr 07 '17 at 09:01