Hello, I'm Sig.  I develop cool things.

Java and the "final" keyword for methods, classes and fields

I was reading some legacy code that had the keyword final sprinkled throughout.  I've always thought that the final keyword was ultimately for saying something like "the buck stops here."  That particular keyword is more for announcing to any future readers and utilizers of your code that there is some intent the original programmer had as to why you don't want to (or should not) extend from this class / method.

While reading some of the legacy code in question, I was spotting the final keyword used in private methods.  Now what in the blazes would a final keyword need to do inside of a private method, you ask?  After a bit of searching the web, I found that optimization is the reason people *think* you should use the final keyword a variety of places.  This is incorrect.  Many blog posts seem to think that the compiler will "inline" methods / classes that have the final keyword sprinkled on them, but this is not the case per this IBM article (http://www.ibm.com/developerworks/java/library/j-jtp1029/index.html) that was referenced in this blog post (http://kirk.blog-city.com/declaring_methods_final_improves_performance_not.htm).

After further thought, I considered that there are a few particular cases that I use with the final keyword.  They are my best practices, as to whether or not they are industry best practices... I'll leave that to the commenters to decide (or decry).

The final keyword should be used to describe a specific intent.  The intent is to say to other programmers who come across your code something along the lines of "hey, new guy/girl... I had a reason for making this method/class/variable final."  Then, the programmer in question reading your code will logically say something like "why?".  This is where the the comments (javadoc, baby!) comes into play.  If a programmer is willing to write a final method or class in particular, there should be some trail of breadcrumbs that future programmers can follow to help them know what the original intent of that design decision was so that whoever is maintaining/modifying the code can make an informed decision as to whether or not removing that little five character word is a good idea or not.