final

I saw this blog post referenced on Hacker News today and thought I’d pounce on one of Stephan’s opinions, which is that the final keyword in Java shouldn’t be used except on fields. I can’t disagree strongly enough with this. I first came across this advice in the O’Reilly Hardcore Java book about five years ago. The book dedicates a whole chapter to the final keyword, which initially surprised me – I didn’t think that the author could possibly have that much to say about it! However, the main idea is “enforced documentation,” which is an argument that really sold me on the concept. I find that whenever I see final on a method parameter, a local variable or whatnot, I have one less question about how that object reference will be used, especially when I’m reading someone else’s code. I know that it was the developer’s intent that the variable in question be assignable or not. I find this to be immensely helpful.

Stephan’s argument is that it impacts readability, but I don’t find that at all. In fact, we make final part of our cleanup process for our default formatter in our Eclipse setups at StyleFeeder. Does final help prevent bugs? Occasionally, yes, but the cases for this are rare enough that I hesitate to put this forth as the main argument in favor of it.

The Perl-ish argument against this is to “avoid putting bars on the windows”, since you never know how things may need to be used in the future. However, that simply doesn’t hold up as a solid argument 99% of the time. The two common use cases for sprinkling final into your Java code are on method parameters (which you should normally not be assigning to) and local variables. In the case of local variables, they are local and the impact of putting final on them is entirely contained within that scope. I have yet to see a reason why this would yield any unwanted side effects. Of course, making classes and methods final is a Big Decision and not what I’m talking about here.

One Comment

  1. Yoav Shapira says:

    I totally agree, Phil.