The final
keyword is can be used to identify specify constant values . That (that is, final
indicates fields that may not be changed during an invocation of a program.The value of public final fields is permitted to be inserted inline into values that cannot change during program execution). However, constants that can change over the lifetime of a program should not be declared public final. The Java Language Specification (JLS) [JLS 2013] allows implementations to insert the value of any public final field inline in any compilation unit that reads the value. This means that if the field's value ever changes, then a compilation unit that depends on the value may still have the old value until re-compiled.field. Consequently, if the declaring class is edited so that the new version gives a different value for the field, compilation units that read the public final field could still see the old value until they are recompiled. This problem may occur, for example, when a third-party library is updated to the latest version but the referencing code is not recompiled.
A related error can arise when a programmer declares a static final
reference to a mutable object (see OBJ50-J. Never confuse the immutability of a reference with that of the referenced object for additional information)Another pitfall arises when static-final
is used inappropriately to declare mutable data. See guideline OBJ01-J. Do not assume that declaring a reference to be final causes the referenced object to be immutable.
Noncompliant Code Example
In this noncompliant code example, class Foo
in Foo
stores a number representing .java
declares a field whose value represents the version of the software being used. It is subsequently accessed by class Bar
, which lives in a separate compilation unit.Foo.java:
Code Block | ||
---|---|---|
| ||
class Foo { public static public final int VERSION = 1; // ... } |
The field is subsequently accessed by class Bar
from a separate compilation unit (Bar.java
):
Code Block | ||
---|---|---|
| ||
class Bar { public static void main(String[] args) { printfSystem.out.println("You are using version " + Foo.VERSION); } } |
When compiled and run, the software correctly prints:
Code Block |
---|
You are using version 1
|
However, a subtle flaw is possible in the future. When the version number must be upgraded, suppose a developer modifies Foo.java, and changes VERSION
to have the value 2. The developer then recompiles Foo.java without recompiling Bar.java. Now the software incorrectly prints:
But if a developer were to change the value of VERSION
to 2 by modifying Foo.java
and subsequently recompile Foo.java
while failing to recompile Bar.java
, the software would incorrectly print
Code Block |
---|
Code Block |
You are using version 21 |
because Bar.java still thinks that Foo.VERSION
is 1.
While Although recompiling Bar.java
will solve solves this problem, a better solution is available.
Compliant Solution
According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 13to §13.4.9, "{{ Wiki Markup final
}} Fields and Constants,"of the JLS [JLS 2013],
Other than for true mathematical constants, we recommend that source code make very sparing use of class variables that are declared
static
andfinal
. If the read-only nature offinal
is required, a better choice is to declare aprivate static
variable and a suitable accessor method to get its value.
Thus a In this compliant solution would be:, the version field in Foo.java
is declared private static and accessed by the getVersion()
method:
Code Block | ||
---|---|---|
| ||
class Foo { static private finalstatic int version = 1; public static publicfinal Stringint getVersion() { return version; } // ... } |
The Bar
class in Bar.java
is modified to invoke the getVersion()
accessor method to retrieve the version
field from Foo.java
:
Code Block | ||
---|---|---|
| ||
class Bar { public static void main(String[] args) { printf(System.out.println( "You are using version " + Foo.getVersion()); } } |
The In this solution, the private version value can therefore not cannot be copied into the Bar
class when it is compiled, thus consequently preventing the bug.
Exceptions
Wiki Markup |
---|
*DCL04-EX1*: According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 9.3 "Field (Constant) Declarations," "Every field declaration in the body of an interface is implicitly {{public}}, {{static}}, and {{final}}. It is permitted to redundantly specify any or all of these modifiers for such fields." |
DCL04-EX2: Constants declared using the enum
type may violate this guideline.
Note that this transformation imposes little or no performance penalty because most just-in-time (JIT) code generators can inline the getVersion()
method at runtime.
Applicability
Declaring a value that changes over the lifetime of the software as final may lead to unexpected results.
According to §9.3, "Field (Constant) Declarations," of the JLS [JLS 2013], "Every field declaration in the body of an interface is implicitly public
, static
, and final
. It is permitted to redundantly specify any or all of these modifiers for such fields." Therefore, this guideline does not apply to fields defined in interfaces. Clearly, if the value of a field in an interface changes, every class that implements or uses the interface must be recompiled (see MSC53-J. Carefully design interfaces before releasing them for more information).
Constants declared using the enum
type are permitted to violate this guideline.
Constants whose value never changes throughout the entire lifetime of the software may be declared as DCL04-EX3: Constants that never change their values throughout the lifetime of the software may indeed be declared final. For instance, the JLS recommends that mathematical constants be declared final.
Risk Assessment
Failing to declare mathematical constants static
and final
can lead to thread safety issues as well as to inconsistent behavior.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL04-J | low | probable | medium | P2 | L3 |
Automated Detection
Static checking of this guideline is not feasible in the general case.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Related Guidelines
C Secure Coding Standard: DCL00-C. Const-qualify immutable objects
Bibliography
Wiki Markup |
---|
\[[JLS 2005|AA. Bibliography#JLS 05]\] "13.4.9 final Fields and Constants", "9.3 Field (Constant) Declarations", "4.12.4 final Variables", "8.3.1.1 static Fields" |
[JLS 2013] | §4.12.4, " |
...
DCL03-J. Properly encode relationships in constant definitions 03. Declarations and Initialization (DCL) DCL05-J. Do not attempt to assign to the loop variable in an enhanced for loop