Optional require(s) NonNull

Stephen Colebourne scolebourne at joda.org
Tue Oct 30 07:27:13 PDT 2012


On 30 October 2012 13:48, Roland Tepp <luolong at gmail.com> wrote:
> The whole point is to make the code safer from NPE's by throwing the
> "optionality" of the value in your face and forcing you to deal with it
> explicitly.
>
> So instead of writing code like this:
>     String someString = ...
>     if (someString == null) {
>         someString = "some default string";
>     }
>     someString.split(...);
>
> you would write:
>     Optional<String> optionalString = ...
>     optionalString.orElse("some default string").split(...);
>
> Much cleaner and easier to understand imho and completely safe from
> accidental NPE.

What is important to understand is that Optional is a religious issue
for many. As much as you believe that Optional is great and should be
widely used everywhere, there are others, like myself, who believe
that widespread use in Java would adversely affect the general
readability of Java code, something which is Java's greatest asset.

AFAICT, Optional is used Stream and only as the return type from 3
methods. It is not used for input types and it is not used for things
such as List<Optional<String>> or input parameters.

To be clear, I believe that the language should provide support for
null. For example, String defines a non-null variable, whereas String?
defines a nullable variable (this is implemented in a variety of other
JVM languages).

Given we don't have null support in the language, the use of optional
in a return type is just about acceptable. However, polluting that
type all over the place, into List<Optional<String>> or method
arguments would be a big negative for me. The key issue is not the
theoretical safety it brings, but the development team issues where
one team uses Optional everywhere and another does not, requiring lots
of copying/conversion of data as the two teams try to call each others
APIs.

As such, I encourage the class to be renamed to OptionalResult<T>.
This expressly discourages the widespread misuse of optionals in
scenarios where they should not be used, such as
List<Optional<String>>, by indicating the correct usage from the
naming.

Stephen


More information about the lambda-dev mailing list