tags:

views:

147

answers:

5
+7  Q: 

Everything's Final

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?

+1  A: 

This is a common idiom for tools like PMD. For example, below are the corresponding rules in Checkstyle. It's really a matter of style/preference and you could argue for both sides.

In my opinion, using final for method parameters and local variables (when applicable) is good style. The "design for extension" idiom is debatable.

Taylor Leese
+2  A: 

final tells the reader that the value assigned first is the same at any time later. Hence a missing final tells the reader that the value will change later, and to take that into account.

Thorbjørn Ravn Andersen
That makes sense for primitives, or for immutable objects like String. But does that encourage a false sense of security for mutable objects?
BlairHippo
A missing final only tells you that it can change later, certainly not that it will. To assume so is simply wrong. If a class is not defined as final it may be subclassed, doesn't mean it is. The usage of final for all variables is open to debate (ofter here) so its absence can just as easily be attributed to coder preference.
Robin
@Robin, please note that the OP said "Everything's final". That is the case I am discussing. Please read the questions properly before downvoting the answers.
Thorbjørn Ravn Andersen
@BlairHippo, only if you do not understand the difference between the reference itself and the referenced object. What you are guaranteed is that the thing you have is the same - what is inside the thing is another matter (but in this particular case, there is a good chance there is a lot of finals too)
Thorbjørn Ravn Andersen
+1  A: 

PMD also has option rules you can turn on that complains about final; it's an arbitrary rule.

If I'm doing a project where the API is being exported to another team - or to the world - leave the PMD rule as it stands. If you're just developing something that will forever and always be a closed API, disable the rule and save yourself some time.

Dean J
+3  A: 
erickson
Seen in hindsight that would have been the best. It would, however, have broken C semantics which was explicitly sought to give C++ programmers an easy transition.
Thorbjørn Ravn Andersen