Effectively final effective?

John Nilsson john at milsson.nu
Thu Feb 25 12:26:48 PST 2010


On Thu, Feb 25, 2010 at 5:57 PM, Reinier Zwitserloot <
reinier at zwitserloot.com> wrote:

> And yet that's what you are proposing: To avoid a simple, obvious, and
> direct error message ("this variable is implicitly final because it is
> accessed from a closure; if you'd like to mutate it, use AtomicReference"),
> you've set up a situation where you implicitly create a copy of a variable,
> and changing the one does not reflect into the other. Horrible, _horrible_
> idea.
>

Just to add to the noise. I strongly disagree. The implicit copy is the most
natural and intuitive semantics of closures in Java IMHO.

Getting rid of "final" just to save some keystrokes sounds very bad to me.
This is one of the best keywords in the language! In argument lists it may
seem somewhat superfluous given that you never expect arguments to be
mutated anyway. So I'm all for adding a rule to Java which makes arguments
implicitly final (I know this won't happen, but I would support it).

However when it comes to local variables I demand from everyone in my team
to always declare every single one of them final. To me it is bad style to
use mutable local variables unless you have a damn good reason for it. And
most of the times, you don't. This policy makes code easy to read and
maintain. I don't have to execute the whole code block in my head to find
out what that variable is used for, I simply looks at it's definition.

Then there is another aspect to it. In my IDE (Eclipse) keywords
are coloured different from types and variable names. It is also the case
that final is a constant in every variable declaration, while the type and
name may change. So the coloured keyword final in a local scope screams
"Variable declaration here!". This also contributes to readability. If
anything, for this very reason, I would like to see the keyword mutable
added to the language, and required as a prefix for non-final declarations.

So to summarize, to me the only reason to _not_ use the final-keyword is to
signal "!DANGER! here be dragons around" when declaring a variable. And one
reason for wanting to do so in the context of lambdas is to allow mutability
of the variable, even if it is to be used as effectively final inside the
lambda.

As Java is today I can only imagine one use-case for this though (but that
can be either because of lack of experience on my part, or lack of lambdas
in Java) and that is for the annoying tendancy for having to declare Files
and Streams and such mutable to have the variable available for the
final-block when closing. But I hear this is being addressed elsewhere in
Java7.

BR,
John


More information about the lambda-dev mailing list