0

I use PMD tool to find errors in java code if any. One common suggestion PMD gives is that "Local variable {local_variable} could be declared final". Is it necessary to declare all local variables as final if it's state is not changed further?

Jeevan Patil
  • 6,029
  • 3
  • 33
  • 50
  • http://stackoverflow.com/questions/1615419/what-is-the-reason-for-these-pmd-rules – Iswanto San Feb 10 '13 at 09:57
  • See also [this discussion](http://stackoverflow.com/questions/316352/why-would-one-mark-local-variables-and-method-parameters-as-final-in-java) – assylias Feb 10 '13 at 10:07

2 Answers2

2

Is it necessary to declare all local variables as final if it's state is not changed further?

No it is not necessary, except in one situation: if you need to access that variable within an anonymous class.

Is it good practice to make all local variable final when they don't change?

This is obviously subjective - I personally think that it clutters the code unnecessarily and that if you follow good coding practice, your methods should be short enough and self-explanatory enough that making your variables final should not be required.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

Well it's also a problem of the language design to set variables explicitly to final and to have the final keyword appear all around. In scala the default is to have everything final and immutable, pushing a more functional design. If you wonder why use final, have a look at scala - that should give you some ideas.

I would consider it bad style not to use final by the way. Final variables - well or constants in that sense - cannot be changed. That is kind of a programming contract. You simply have less side-effects in code with final variables. If you leave that out you could also leave out all the private fields. Why bother?

In eclipse you can add all the required final fields and lots of other things considered "cleaner" automatically, when you open the dialog "Source/Clean Up..." (so I guess it's called "Clean Up" because not using final would be considered unclean).

It's up to you - use it - or leave it. Use it - and look especially at the code where the final could not be applied. Maybe that code could be improved to be final?

So: Yes! It is good practice!

michael_s
  • 2,515
  • 18
  • 24