I’ve been using PMD to help spot potential problems in my Java code, and I’ve been finding its advice to be split between the useful, the idiosyncratic, and the “WTF?!”.
One of the things it keeps telling me to do is to use the final keyword for literally every variable I can attach it to, including input parameters. For actual constants this seems sensible, but for other stuff it just strikes me as odd, possibly even a tad counterproductive.
Are there concrete advantages/disadvantages to hanging final on every variable declaration you possibly can?
“Every variable declaration you possibly can” sounds a bit extreme, but
finalis actually beneficial in many ways. Sometimes I wish thatfinalwas the default behavior, and required no keyword, but true “variables” required avariablemodifier. Scala adopted something like this approach with itsvalandvarkeywords—usingval(thefinal-like keyword) is strongly encouraged.It is especially important to carefully consider whether each member variable is
final,volatile, or neither, because the thread safety of the class depends on getting this right. Values assigned tofinalandvolatilevariables are always visible to other threads, without using asynchronizedblock.For local variables, it’s not as critical, but using
finalcan help you reason about your code more clearly and avoid some mistakes. If you don’t expect a value to change within a method, say so withfinal, and let the compiler find unnoticed violations of this expectation. I’m not aware of any that do currently, but it’s easily conceivable that a JIT compiler could use this hint to improve performance too.In practice, I don’t declare local variables
finalwhenever I could. I don’t like the visual clutter and it seems cumbersome. But, that doesn’t mean it’s not something I should do.A proposal has been made to add the
varkeyword to Java aimed at supporting type inference. But as part of that proposal, there have been a number of suggestions for additional ways of specifying local variable immutability. For example, one suggestion was to also add the key wordvalto declare an immutable variable with inferred type. Alternatively, some advocate usingfinalandvartogether.