A disclaimer or two for Optional
tim at peierls.net
Sun Oct 20 07:54:30 PDT 2013
On Sun, Oct 20, 2013 at 9:13 AM, Doug Lea <dl at cs.oswego.edu> wrote:
> On 10/19/2013 03:38 PM, Tim Peierls wrote:
>> I suppose there's no harm in adding this, but I think most people already
>> that a reference to an Optional isn't a meaningful value.
> The reaction of others seems to argue for adding the wording.
> Most people know that comparing Integers via "==" is
> almost always wrong. (So wrong that autoboxing normally
> rescues you from this if one of the arguments is an int.)
> And most people would not even think to do
> synchronized(Integer.valueOf(**aNumber), and would if asked
> think that it is such a terrible idea that it is a good
> candidate to being outlawed.
> But most people haven't noticed that the same issues apply
> even moreso to Optional.
I think the opposite is true: People are more likely to make mistakes
because of autoboxing than they are to write code that synchronizes on
Optional instances or compares Optional references.
The virtue of Optional, in my experience with the Guava variety, is that
the compiler never lets you forget that you aren't dealing with a Foo,
you're dealing with a (probably lightweight, possibly magical) potential
container of a Foo. It's no more tempting to say "synchronized
(optionalFoo)" than it is to say "synchronized (singletonFoo)". Maybe even
less tempting, because a singleton at least has a (misleading) whiff of
permanence, whereas an optional thing might not be there at all.
It's fine to warn people in general about the potential pitfalls that exist
today or that might arise in the future due to new language features. It
just seems strange to focus on Optional, a class whose name practically
shouts to the user, "Don't synchronize on me!"
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the lambda-libs-spec-experts