Wednesday, December 4, 2013

When to make a method final in Java

Final keyword in Java is not as mysterious as volatile or transient, but still it creates lot of doubts on programmers mind. I often receives questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this is not trivial, knowing what a keyword does is just small part of mastering that functionality. Similar to real world, where knowing that a sword can cut lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use if effectively. Final keyword can be applied to class, methods and variable and has different meaning for each of them, but the motive remains same, it state completeness, it opposes change. For example, final class can not be extended, value of final variable can not be change and a final method can not be overridden in Java. This gives you first hint, when to make a method final in Java, obviously to prevent subclass for changing it's definition, technical preventing it from overridden. There are lot of clues on How to use final keyword on methods in Java API itself, one of the prime example of this java.lang.Object class, which declares a lot of method final including wait method with timeout. Another example of making a method final is template method, which outlines algorithm in Template method design pattern. Since, you don't want a sub class to change the outline of algorithm, making it final will prevent any accidental or malicious overriding. In this tutorial, we will learn few things, which will help you to effectively use final keywords with Java methods.



Final method in Java

Why make a method final in Java
One of the best practice which I learned from clean code is about good designs, which mandates and ensures things, rather than listing some guidelines. Prime example of this is clone() method, whose correct implementation depends upon following some guidelines, which is not ensured by system. By making a Java method final, you not only indicate, but also ensures that no one can it's definition. This is particularly important while dealing with sensitive method, which deals with security and critical functionalities. Template method pattern is a good example of when to make a method final. In template method pattern, outline of method is captured in one method but hooks are provided to add flexibility in implementation. By making template method final, we ensure that steps defined in algorithms are exactly followed by each class, but gives them flexibility to define step in there own term. By the way, in Java, making a class final, automatically ensures that all it's method can not be overridden, which is equivalent to making them final. Making a class final is also an important step to create Immutable class in Java.


Here are few guidelines, which can be helpful to decide, when to make a method final :

1) Methods which are called from constructor should be final, otherwise a subclass may override and alter the behavior of method, which may result in surprise and undesirable behavior.

2) Consider making performance critical method final, this given compiler more opportunity to optimize it. Compiler may inline or cache such methods because they can not be changed during application life time. Though modern JIT are even capable of in-lining non final method, if they think it can result in performance gain and it's not overridden, making a method final can do this in-lining even before JIT comes into picture.

3) Sensitive methods, whose behaviors are deemed complete and which are not supposed to be overridden, should be final.

4) Consider making template methods final, while using template method design pattern.

In short, making a method final is mainly driven by design and safety requirement. Though performance can also be consider one of the reason, it is not the main reason in today's Java world of advanced JIT. It's also a good idea to document, why you made a method final, that will help developer, who will maintain your code. There is also another doubt about making a private method final or not. Since private method can not be overridden, neither in subclass, where it's not accessible, nor in inner class where it's accessible, because they are bonded using static binding using class name. Making a private method final doesn't provide any additional value.


That's all on this Java tutorial about when to make a method final in Java. Main reasoning behind making a method final is to prevent it being overridden by subclasses. By making a method final, you not only indicate but also ensures that your tried and tested method is not overridden. As a best practice of prevention, any security sensitive method related to authentication and authorization should be final. Similarly critical methods, which defines critical functionality like template method must be final. Last, but not the least, any method which is called from constructor must be final to avoid any surprise, which may result due to accidental or malicious overriding in subclass.

3 comments :

Sandeep malviya said...

can u share me ur knowledge of java performance and tuning with optimizer(how jvm working with bytecode with taking the consideration with performance ) it thr any article or books...ple lemme knw ...........Thnaks in advance

Anonymous said...

You must absolute make a method final if it is doing any kind of security checks, because non-final method , who performs security checks can be overridden in a way that bypass security. For example, a child class can override a non-final method to bypass security checks done in the parent class. Following code is bad for this reason

class SensitiveClass{

public perform(SensitiveAction e){
doSecurityCheck();
// do something

}

protected void doSecurityCheck() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new sesnsitivePermission("sesitiveAction"));
}
}

}

SARAL SAXENA said...

@Javin Nice article just want to add that..

Final keyword has a numerous way to use:

A final class cannot be subclassed.
A final method cannot be overridden by subclasses
A final variable can only be initialized once
Other usage:

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class
A static class variable will exist from the start of the JVM, and should be initialized in the class. The error message won't appear if you do this.

Post a Comment