capturing (or not) mutable local variables

Stephen Colebourne scolebourne at joda.org
Sat Nov 27 03:54:08 PST 2010


On 26 November 2010 17:13, Mark Mahieu <markmahieu at gmail.com> wrote:
> On 26 Nov 2010, at 10:58, Doug Lea wrote:
>> The workarounds like using 1-slot arrays add a level of
>> indirection to subvert the shallow-only provision.
>> Which seems tolerable.
>
> It's tolerable if the workaround is employed with a good understanding of its limitations, but it has become a common approach to simple inconveniences with final variables used in relatively innocuous contexts.  My fear is that it's a workaround which will find itself used in far less tolerant situations through the simple virtues of being well known and long established.

Agreed. And there is a connection to generics wildcards too. In both
cases, restrictions were/are added to the language for good reasons -
to keep the language safe. (For generics I'm thinking of casting a
List<Integer> to a List<Number>, and many other cases as in the huge
FAQ). What happens is:
- the developer tries to perform the "bad" thing
- the compiler stops them
- the developer curses the compiler
- the developer finds the quickest hack
In my experience, most don't worry about WHY the thing was "bad" they
just learn the hacks (and aren't worried if the hack is safe). For
generics, that might be using a raw type. For no access to mutable
variables, its the length one array.

While I can entirely see why the mutable variable restriction is
desirable from a correctness POV, I'm far from convinced that it is
beneficial from a practical POV, and may actually be harmful (because
only a fraction of developers understand the restriction). As such,
allowing mutable access may well be better overall. Although, some
kind of middle ground like Doug suggests would be good.

(Note that it could be argued based on the above, that mutable access
via arrays should be blocked to force an object based workaround like
AtomicRefs)

Stephen


More information about the lambda-dev mailing list