DEV Community

John Mercier
John Mercier

Posted on

marking parameters and local variables as final

In a few projects at work everything is declared final. Even parameters and local variables. I believe this is done through a setting in intellij.

This seems excessive so I wanted to find a style guide that justifies this style. I couldn't find one. In fact, very few guides mention this style in a positive way. There is a guide for the jdk that describes some rare cases where this style applies.

Method parameters and local variables should not be declared final unless it improves readability or documents an actual design decision. Fields should be declared final unless there is a compelling reason to make them mutable.

Motivation

Writing out modifiers where they are implicit clutters the code and learning which modifiers are implicit where is easy.
Although method parameters should typically not be mutated, consistently marking all parameters in every methods as final is an exaggeration.
Making fields immutable where possible is good programming practice. Refer to Effective Java, Item 15: Minimize Mutability for details.

The google style guide does not mention using final for parameters and local variables.

The twitter styleguide does not directly mention using final for local variables or parameters but the examples only use final for fields.

Oracle's coding conventions does not mention making parameters or local variables final.

After checking several other style guides I have not found anywhere that states parameters and local variables should always be declared final.

Prior to java 8 local variables needed to be declared final when used in an anonymous inner class. This was changed in java 8 with the concept of effectively final variables. Since java 8, effectively final variables do not need to be marked as final. This is explained in the Java Language Specification.

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

It also explains that the final modifier can be removed from code that declares parameters and local variables as final.

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

I believe this is where the suggestion in the first style guide applies. Parameters and local variables should only be declared final to improve readability or to document a design decision. They should not be declared final to "check a box" in a static code analysis report.

Top comments (0)