Wednesday, May 23, 2007

final - Least used keyword in Java development?

I've been writing Java code for a long time and I never thought about making a class or a method final until recently. Actually the only place the final keyword was used was when declaring constants. I still don't think you will gain much on performance by using final but the biggest selling point is the correctness it brings to the code.

So far our development team has not looked at the correct usage of final keyword during peer reviews, but going forward it will be added to the peer review guideline document. Hope I'll see more finals in our code after that [if anyone follows the guideline that is :) ]

Anyway here is a link to a good explanation on final keyword: The Final Word on the final Keyword

Don' forget to click the +1 button below if this post was helpful.

5 comments:

Dan said...

I'd say that final is probably one of the most used keywords, certainly in my own code.

Always make each field of a class final unless you have a good reason not to.

Final classes and methods are less straightforward. It depends on how you intend the class to be used.

As for the least used keyword in Java, that has to be 'strictfp', probably followed by 'volatile' and 'transient'. Personally I've never used 'continue'.

Tom Hawtin said...

final on method and classes doesn't actually make any difference on a modern JVM (well, perhaps on Java ME VMs). Sun HotSpot, for instance, after verification only uses it when compiling to short circuit a check to see whether there are subclasses the override - the same code is generated whichever.

final on fields is a must, where ever possible. It's not necessarily a bad idea of local variables.

Master of Nothing said...

@Dan

I guess the proper title would have been 'most under used keyword'. You are probably spot on about the least used keywords.

Scott said...

Performance was always a terrible reason for using final and a moot point these days. I've needed to override pieces of libraries and been completely stuck because all their parameter types are final classes.

I hadn't thought about it as a way of enforcing composition (as mentioned in your link) but that's about the only good reason I can think of for using it in an app - just make sure there is a corresponding interface.

Javin @ grep command in unix with examples said...

This should be the most used keyword in Java :) because it makes life easier specially if you are writing multi-threaded high performance concurrent code.

Javin
What is synchronization in Java