Stream proposal and null results

Brian Goetz brian.goetz at oracle.com
Thu May 17 16:09:32 PDT 2012


> FWIW, I think that the Option<T>  approach to null handling would be a
> big mistake in Java.
>
> What you end up with in that strategy is deeply nested generics like
> Map<Optional<String>, List<Optional<Integer>>>

In the context of the discussion we're having, which is whether to use 
Optional<T> as the return type for Stream<T>.getFirst, this is not an 
issue, because the option-ness is likely to be hidden by the chaining:

   String s = people.filter(p -> p.age() > 18)
                    .map(Person::getName)
                    .getFirst()
                    .getOrThrow(() -> new NoSuchPersonException());

Here, the Option has relatively little use on its own; you're going to 
immediately call one of the various getOrElse methods, and the fact that 
it is an Option<String> does not appear in the source code.

Similarly, if we added an Option-bearing get-like method to Map (not 
saying we're going to do this), the same would be true:

   String s = map.getAsOption(key)
                 .getOrElse(DEFAULT_STR);

Since we're not proposing anything that returns List<Optional<T>> or 
anything like that, I don't get how your argument applies here, and it 
almost sounds like you're making the argument of "don't add any new 
generic container-like types to the library, because you increase the 
chance that people will use unwieldy generic names", which I can't say 
makes very much sense to me.  It might be poor taste to have a 
nineteen-deep nested list of lists, but does that mean we shouldn't give 
people a generic List class?

> I have a guidance rule that 1 level of generics is OK, 2 is
> manageable, but 3 means you're probably missing a real domain class.
> Optional<T>  just gets you to that 2nd/3rd layer of generics faster
> than necessary. I'd also note that those nested generics tend to be
> harder for developers to rationalise about.

That's a fine rule for your code.  I just don't see how adding 
Optional<T> and adding a few methods that return Optional<T> move people 
any closer to violating that rule?



More information about the lambda-dev mailing list