Open cbeams opened 6 years ago
Finally found how to change the behavior in IntelliJ when you extract a variable (it makes it final by default). The checkbox is enabled by default:
Disable it and IntelliJ remembers the decision.
that sounds like a strange rule to me. immutability is important, in kotlin or scala everything is a val (const=final) by default and vars are very rare. mutable variables are a code smell, and usually a sign that you should rewrite in a more functional way.
It is highly desirable to declare member variables (both static and instance) as
final
in order to advertise and enforce the statelessness and immutability of a given class. It is, however, not desirable to declare local variables asfinal
for the following reasons:It is not the idiom in Java to do so. This is not to say that people never do it, but that if you scan the majority of large, popular open source Java codebases, you will find that most local variables are not declared
final
, and that where they are, it is done in a way inconsistent with the rest of the codebase.There is typically no need to declare local variables as final. There are certain cases, such as when a variable is declared and then subsequently used within an anonymous class, but this is rare, and even more rare since Java 8 and lambda expressions, which transparently handle local variables as "effectively final" without any explicit
final
modifier necessary.If
final
is considered "necessary" because you want or need to prevent mutation, your method is probably too complex. Methods should be simple and typically quite short. There should be no need to "enforce" immutability of a local variable in the context of a method. Its purpose should be obvious, and it should be obvious if overwriting the value of the variable is the wrong thing to do.Applying the
final
modifier to local variables creates line noise without creating any value. The use offinal
on local variables is doubly distracting to the reader, (a) because it is that many more characters that the reader needs to parse and (b) because as noted in (1) above, it is non-idiomatic to see, meaning that it catches the reader's eye all that much more, and makes them wonder (needlessly) "why is this variable declaredfinal
?", only to eventually realize that it didn't need to be final at all, and that this modifier was just a waste of their time.Java 10 introduces the reserved type name
var
for convenient declaration of local variables, but there is no way to declare avar
as final (whereas in Scala, for example, this is done with a distinction betweenvar
(mutable) andval
(immutable) declarations). This means that in Java 10, it will become even less idiomatic to seefinal
local variables, and that you'd need to really go against the grain to declare them that way.