omsn.blog

Java devs: why you should use the final modifier more often

Java developers barely use the final flag. The reason is that final has no affect on the correctness of a program. If you take an existing Java program and remove all the final keywords, it will still run correctly (EDIT this statement is not entirely true). So why even bother about it?

Because final can help you write faster and more stable programs. Here is how:

Avoid NullPointerExceptions caused by uninitialized fields

Everyone has written a class like this:

Can you spot the error? Right, you'll get a NullPointerException whenever you call the get() method, because you forgot to initialize the cache field. You could have easily avoided this run-time error by declaring each field — of which you already know will only be initialized once — as final:

By declaring the field to be final, you moved the error from being only detectable at run-time to a compile-time error, because final fields have to be initialized during object construction. Applying this technique every time you write a new class will make your code more stable and less vulnerable to random crashes.

Increase performance

The most important reason why you should use final is the performance benefit. Marking methods as final is the Java-way of declaring a method non-virtual, which — by definition — cannot be overwritten by sub-classes. So whenever the JVM stumbles over a final method, it can call it right away without additional checks to make sure it executes the correct one. It also makes the method a better candidate for inlining, which can enhance your app's performance drastically.

A good candidate for final methods are getter/setter methods and little helper functions which are shared between two or more other methods. These functions are very unlikely to be overwritten by sub-classes so it's almost always safe to mark them final directly at the time of writing them. You can always remove the final keyword later when you need to overwrite it.

You can also declare the whole class as final. That means the class cannot have any sub-classes, so all methods of a final class are automatically final as well.

Be careful though with marking your classes final in case you are developing a framework rather than an application. The people using your framework occasionally want to override classes which might not be intended to be sub-classed by the framework author in order to get their stuff working.

I hope this article helps you write better Java code. Any additional nice use-cases of final I have missed?


comments powered by Disqus