The final keyword
Here's a post I made recently on the Pragmatic Programmer's list:
The final keyword is a personal pet peeve of mine in Java. First off, it's
meaning is overloaded. If you use final in talking about variables, then it
means that once you assign a value to the variable that it will not change.
I have no qualms about using it for this purpose. The other usage of final
is on class and methods and it's meaning there means to "seal" the class or
method from being subclassed or overridden. Now, originally, this was done
for the "sake of speed and security". The VM can make a lot of shortcuts if
it knows a class is final and thus get speed improvement. This is also true
for final on methods. Basically, the VM does not have to do a method lookup
for finals. The security part comes into play in that some one can not
override your method or class and provide their own implementation. I think
either way is EVIL! Why would I say such a statement? Basically, I think by
using final you are effectively saying, "I have produced the most perfect
code ever known to man. No one will ever ever want to change or enhance this
code since it is SO PERFECT!" Now, I don't know about you, but I don't write
perfect and wouldn't ever claim to either. I have ran into too many
situations where I needed to override a final method or class. It's
anti-object think. You never know what people are going to do with your code
and what they might want to do with it. I hate the private keyword on
methods for this exact same reason.
Monday, September 08, 2003
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment