3

I'm a bit confused, my Intellij Idea warns me if no final modifiers everywhere when possible.

Actually final is very good option, and of course its needed in lots of cases like methods parameters, constants and ... ,

But ...

Probably there are some really strong arguments why my local method variables should be final ?

Could you pls help me understand a benefit of such mass final usage ?

Yura Galavay
  • 426
  • 6
  • 10
  • 1
    Possible duplicate of http://stackoverflow.com/questions/316352/why-would-one-mark-local-variables-and-method-parameters-as-final-in-java – Andy Turner May 06 '17 at 13:40
  • one more thing im thinking, in my undertanding final previously had some "special meaning", it even has a sense to describe some API specifics etc... Now looking at final everywhere, i think this sense is kind of lost. – Yura Galavay May 06 '17 at 13:40
  • 2
    IMHO, making parameters and local variables final just adds a whole lot of noise in the code, making it more verbose and harder to read, without any real advantage. – JB Nizet May 06 '17 at 13:40
  • 1
    Making local variables `final` helps you reason about variables because you know the value is never assigned; but there is a school of thought that if you *really* need to do that for reasoning purposes, your method is probably too big anyway. – Andy Turner May 06 '17 at 13:42
  • 1
    Some people just make a superstition out of best practices. "Immutable is good, so `final` everywhere must be better." The idea is that code maintainers will save time not worrying about whether a variable's been reassigned. IntelliJ apparently bought into this idea. I am not aware of any _evidence_ that `final` everywhere provides a net benefit, but I haven't seen any harm from it. I personally like to put `final` on local variables that are otherwise "effectively final", but I admit to being superstitious there. – Lew Bloch May 06 '17 at 18:12
  • I'll bet you can turn this off if you prefer. My IntelliJ does no such thing for me. Check out the global settings. – duffymo May 06 '17 at 19:48

1 Answers1

3

A benefit of making all variables final is that it is clearly visible which variables are assigned only once. Another is that it is possible to use such a variable in an anonymous class without having to make it final (because it already final but this benefit has disappeared with Java 8).

Both of the benefits above are not very strong, so perhaps you just want to disable the Local variable or parameter can be final inspection. This inspection is disabled by default, so you may have enabled it by accident?

Bas Leijdekkers
  • 23,709
  • 4
  • 70
  • 68