Java: How to make local fields & parameters final without having a ‘final’ keyword on each declaration

coding-stylefinaljava

By default, I want all my local variables and method parameters to be final. Unfortunately, the Java language designers chose a different default: variables&parameters are by default non-final, and final variables&parameters need to be declared with the final keyword. So I need to add lots of finals. (And obviously I don't do this manually, but have my IDE add them for me.)

So I end up with source code where every default case is marked, whereas exceptions to my preferred default are barely visible. For readability, I would like it to be the other way round, i.e. only non-final local variables and parameters should be marked/highlighted/annotated/…

Is this possible?

I'm open to solutions that integrate at different levels, e.g. folding within the editor, style checkers, build steps, etc…

Best Answer

I think your intention in making all local variables final is very good practice, but doing so implicitly (i.e. not explicitly with the final keyword) is a bad idea.

Rather than worry about readability for yourself, think about future maintainers of your code: will anyone reasonably expect that reassigning a field without the final keyword will fail to compile?

It looks like you can automate the inclusion of final keywords in Eclipse during code generation, but using a style checker to enforce it may highlight more false positives than it's worth.

If you're open to exploring other languages and paradigms, many functional languages default to immutability.

Related Topic