geode-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Bill Burcham <>
Subject Re: Unnecessary uses of final on local variables
Date Tue, 18 Jun 2019 00:33:56 GMT
The final keyword is not redundant—quite the opposite—it's extremely

Local variables are not, in general, final, unless you declare them as
such. That being the case, it is not redundant to declare local variables

What the compiler will do for you, is _if_ it can ensure that a local
variable (or method parameter) is never modified (after initialization)
then that variable is treated as "effectively final". Variables that are
explicitly declared final, or are determined to be "effectively final" may
be referenced in lambdas. That's a nice thing.

I would like to offer a counter-recommendation: *final should be the
default everywhere for fields, for method parameters (on classes, not on
interfaces), and for local variables*.

Many benefits would accrue to us, should we adopt this default:

1. final fields must be initialized in a constructor and never mutated
again. This makes reasoning about those fields easier.
2. classes that have all their fields final are immutable and hence easier
to reason about: they can be passed between threads, for instance, with no
need to protect from races
3. final method parameters can never be mutated, making them easier to
reason about
4. final local variables can never be mutated, making them easier to reason

When final is the rule, non-final is the exception. Another way of saying
that is that when final is the rule, mutability is the exception. That is
as it should be. *Mutability is the enemy*.

I have turned on a couple IntelliJ settings that make this the default for
me. I encourage you to do the same:

First there are these two "Code style issues" in the Java inspections:

"Field may be 'final'"
"Local variable or parameter can be final"

[image: image.png]

Then there is this setting will cause newly-defined variables created via
the "Extract variable" refactoring:

If you select that check box (after selecting those inspections settings
above), it'll declare the newly-introduced variable "final" and it'll
remember the setting the next time you invoke "Extract variable" refactoring

[image: image.png]

  • Unnamed multipart/related (inline, None, 0 bytes)
View raw message