Finality in Java
Posted by Mike Haller
on Tuesday, August 7. 2007
at 00:38
in Java
A collegue developer has some fine coding style and I'm trying to adapt it as much as possible.However, there was one thing which made me wonder: using the
final keyword in interfaces.To be more specific, in the method parameters like this:
public interface IMyInterface {
void doSomething( final Object object );
}
As I didn't know much more than the standard stuff about the implications of using
final, I began to dig a little and present my conclusion here.
Besides the usual stuff everybody knows about final, like that it's used for compile-time constant values or to prevent a Class from being subclassed or a Method from being overridden, there are other effects final is good for.- The "final" keyword has no effect when used for parameters in interface method signatures. In fact, the "final" keyword is not part of a method signature at all, so its an implementation detail. Comparing the byte code for two interfaces, one with final parameters the other without, shows no difference.
- Using final improves code robustness in software engineering. That's the the reason to use final. Use it to make classes immutable (the class, all methods and all fields are final, no setters, getters return only copies). Use it to enforce composition over inheritance. Bad bad inheritance! See "Fragile Base Class problem"
- It's outdated information that making a method "final" would improve performance, as all modern VMs automatically detect that kind of optimizazions: e.g. using the faster "static invocation" for not overriden methods is done automatically, no need to use final
- Private and static methods are implicitly final
- Final can improve performance and memory usage when used on fields, as the compiler can optimize more aggressively
So, I conclude that it does not make sense to use "final" in the parameters in interfaces. There might be the effect that it somehow looks more familiar with the "final" keywords.
See http://renaud.waldura.com/doc/java/final-keyword.shtml
