By bloid
via stephan.reposita.org
Published: Apr 22 2008 / 11:22
I haven’t been using the final keyword in Java for 10 years, but more and more I think it’s an excellent keyword in Java. All local variables should be declared final. Today one of the developers of my team made every local variable in a method final and I was wondering how strange that looked. But of course it was the right thing to do.
Comments
Umberto Zappia replied ago:
The Final variable is one of the most under used features in Java (for some programmers)
Use the Final modifier on instance-variable definitions to create immutable internally accessible objects.
ChiralSoftware replied ago:
In fact, I think that the "final" keyword should never have existing in Java. It should have been by default that all "variables" are final, and not really "variable". They should have had another keyword like "variable" or "mutable" which you put on the few specific vars that you are explicitly saying, "these can be modified". The smart thing is to have minimum possible accessibility of whatever you're working on. That means, only declare a variable in the scope it is needed. Make things private if they don't need to be accessed outside the class. And make every variable final unless it's explicitly ok for it to be mutated. So "final" should have been an implied default setting, with "mutable" being an explicitly-declared extra level of access.
M Easter replied ago:
Generally, I think using final in such a blanket way in Java is not enough bang-for-the-buck. Give me unit tests. See my comments on the blog.
dzonelurker replied ago:
The 'functional' hype has reached the mundane Java territory. All variables must be final (a contradiction in terms but who cares), states and assignments are evil, we NEED closures, ...
Umberto Zappia replied ago:
@dzonelurker
I thought you were against "closures proposal" in Java 7.
dzonelurker replied ago:
But WE need closures! Otherwise we will be doomed!
Tantalus replied ago:
Indeed. Quick, someone write a blog post about how Java needs currying, partial application and macros.
dglasser replied ago:
I'd like to see a show of hands from the people who voted up this post. Who among you is planning on adopting this practice from now on?
kieronwilkinson replied ago:
We do it here as standard. It's quite nice when you get used to it. I can understand some people wouldn't from the bang-for-the-buck argument though.
kellyfj replied ago:
Tried it once - made sense - but the code ended up looking awfully unreadable. So I stopped and figured time was better spent unit testing.
Voters For This Link (22)
Voters Against This Link (13)