Loose ends: Optional

Remi Forax forax at univ-mlv.fr
Mon Jun 10 03:18:26 PDT 2013



>> Regardless the option chosen above,
>>    - Optional should not implement Iterable or have a forEach method. It
>> makes the code weird to read.
>
> Sam made a very compelling argument for forEach based on experience at 
> Twitter over lunch last week.  I'll summarize, but Sam please correct 
> me if I mangle it.  Basically: in their library development efforts, 
> there were a lot of "unrelated" containerish classes (including a 
> variant of Optional), which each had their own class-specific method 
> names.  Over time, the method names converged to a common vocabulary 
> (filter, map, forEach) even though they had no common supertype, and 
> as a result, the perceived usability went way up.
>
> The current ifPresent(Consumer) is something I pulled out of a hat and 
> the name does not connect to anything.  On the other hand, 
> forEach(Consumer) is familiar from a lot of other classes.  I prefer 
> forEach, on the theory of not introducing new names for new stuff.  (I 
> already hate the forEach / forEachRemaining distinction between 
> Collection and Iterator, and don't want to make this problem any worse.)

I like this distinction because forEach and forEachRemaining doesn't 
have the same semantics,
naming two different things with the same name and everybody is lost.

If you don't like ifPresent, fine, we can try to find another name. But 
not forEach, iterating over an Optional is weird (see below).

>
> The "don't implement Iterable" and "don't call it forEach" all feel 
> like they are motivated by "make it less useful so people won't be 
> tempted to use it as much."

Again, No, the EG votes to have Optional, I respect that.
Now it's not because the EG has voted to have Optional that I will let 
you cripple it.

So the real issue is code like this:
Optional<List<String>> list = ...
for(List<String> l:list) {
   ...
}



> There's a (possible) value in that Optional; giving users multiple 
> reasonable ways to get it at means they have to distort their code 
> less to use Optional effectively.

Yes, users may want to see Optional as a collection,
that's why I said that in that case Guava method toSet() is what we 
should include in the JDK.

[...]

>
>>    - filter doesn't seem to pull it's own weight, for what it worth, I
>> never use it on an Option in Scala.
>
> Agreed this is probably the least useful of the bunch, but again, 
> can't be easily added with fluency by users, the semantics and 
> implementation are obvious, and its absence might look weird given few 
> things support map but not filter.

I prefer,
   optional.toSet().stream().filter(),
it's fluent, lazy and not that bad given that it's not a primary use case.

Rémi



More information about the lambda-libs-spec-experts mailing list