Should ‘Final’ Be Used for Parameters and Locals in Java?

coding-stylefinaljava

Java allows marking variables (fields / locals / parameters) as final, to prevent re-assigning into them. I find it very useful with fields, as it helps me quickly see whether some attributes – or an entire class – are meant to be immutable.

On the other hand, I find it a lot less useful with locals and parameters, and usually I avoid marking them as final even if they will never be re-assigned into (with the obvious exception when they need to be used in an inner class). Lately, however, I've came upon code which used final whenever it can, which I guess technically provides more information.

No longer confident about my programming style, I wonder what are other advantages and disadvantages of applying final anywhere, what is the most common industry style, and why.

Best Answer

I use final the same way as you. To me it looks superfluous on local variables and method parameters, and it doesn't convey useful extra information.

One important thing is that strive to keep my methods short and clean, each doing a single task. Thus my local variables and parameters have a very limited scope, and are used only for a single purpose. This minimizes the chances of reassigning them inadvertently.

Moreover, as you surely know, final doesn't guarantee that you can't change the value/state of a (nonprimitive) variable. Only that you can't reassign the reference to that object once initialized. In other words, it works seamlessly only with variables of primitive or immutable types. Consider

final String s = "forever";
final int i = 1;
final Map<String, Integer> m = new HashMap<String, Integer>();

s = "never"; // compilation error!
i++; // compilation error!
m.put(s, i); // fine

This means that in many cases it still doesn't make it easier to understand what happens inside the code, and misunderstanding this may in fact cause subtle bugs which are hard to detect.

Related Topic