Think twice before declaring a Java method as final

If you create classes that may be used by other developers, declaring methods as final will make them not overridable in the subclasses.

 

While today, it may seem obvious to you that a particular method will never ever need to be overridden, you might not properly predict all use-patterns of this class. If this happens, some other developer will have to jump through the hoops to create another version of such a method in a subclass. If you don’t want to be cursed in the future, think twice if you really really want to declare this method as final. Do you see any benefits in using final methods?
We had to extend a third party library to improve their implementation of a certain networking protocol. As it usually happens, the code was poorly documented, so we had to read the code to find out which method to override in the subclass. Sure enough, that method was declared as final.

We found a workaround and still replaced the call to the final method to the call to our own. So what the original developer achieved by using final? He made our work more difficult than it should have been.

 

Originally, Java compiler was optimizing (inlining) final methods. Today I’ve learned (thank you, Heinz) that Java compiler doesn’t do it anymore, and they are optimized by the Hotspot JVM:

http://www.javaspecialists.eu/archive/Issue157.html
http://www.javaspecialists.eu/archive/Issue158.html

Who are these guys we’re protecting from by using final? BTW, I also believe that the keyword protected is equally useless.

 

Yakov Fain

2 thoughts on “Think twice before declaring a Java method as final

  1. I’ll second that 😛 I had to extend a particular software (OpenChord) only to find out that all the classes I had to extend were all final…and yes…i literally cursed the authors 😛 (just kiddin’, but it would have been nice to think about people reusing their stuff)

  2. Then I’m third. :)
    “Final” and “Private” should be used with extreme care by library developers. “Monkey patch” http://en.wikipedia.org/wiki/Monkey_patch is an option of last resort when extending library code, but, unfortunately, I have to resort recently to this option way too often when extending Flex components. The only excuse for this restrictive final/private usage is security considerations or rare strict runtime semantic (think of Number subclasses or String in Java). The “code hiding” option is used inappropriately by majority of library developers — and this violates the whole purpose of libraries created. Libraries should be developed for reuse and extension, not for restrictions.

Comments are closed.