The final
keyword can be used to specify constant values (that is, 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 values value of any public final fields field inline in any compilation unit that reads the 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 re-compiledrecompiled. 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 guideline "VOID OBJ02(see OBJ50-J. Never conflate confuse the immutability of a reference with that of the referenced object" for additional information).
Noncompliant Code Example
In this noncompliant code example, class Foo
in Foo.java
declares a field whose value represents the version of the software. The field is subsequently accessed by class Bar
from a separate compilation unit.Foo.java
:
Code Block | ||
---|---|---|
| ||
class Foo {
public static 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) {
System.out.println("You are using version " + Foo.VERSION);
}
}
|
When compiled and run, the software correctly prints
Code Block |
---|
You are using version 1
|
However, But if a developer changes were to change the value of VERSION
to 2 by modifying Foo.java
and recompiles subsequently recompile Foo.java
, but fails while failing to recompile Bar.java
, the software would incorrectly prints:print
Code Block |
---|
You are using version 1
|
Although recompiling Bar.java
solves this problem, a better solution is available.
Compliant Solution
...
According to [§13§13.4.9, "{{final
}} Fields and Constants" |http://java.sun.com/docs/books/jls/third_edition/html/binaryComp.html#13.4.9] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\]," 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.
Consequently, a In this compliant solution is:, the version field in Foo.java
is declared private static and accessed by the getVersion()
method:
Code Block | ||
---|---|---|
| ||
class Foo { private static final int version = 1; public static final 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) { System.out.println( "You are using version " + Foo.getVersion()); } } |
As a resultIn this solution, the private version value cannot be copied into the Bar
class when it is compiled, consequently preventing the bug. Note that this transformation imposes little or no performance penalty because most just-in-time (JIT) code generators are capable of inlining can inline the getVersion()
method at runtime; consequently there is little or no performance penalty incurred.
Exceptions
Wiki Markup |
---|
*DCL04-EX1*: According to [§9.3, "Field (Constant) Declarations" |http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.3] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\],
"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." |
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).
DCL04-EX2: Constants declared using the enum
type are permitted to violate this guideline.
DCL04-EX3: Constants whose value never changes throughout the entire lifetime of the software may be declared as final. For instance, the Java Language Specification 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
[JLS 2013] | |||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="cefca2b5-c69f-4310-9ff5-92c8f2f63d49"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§13.4.9, "final Fields and Constants" | http://java.sun.com/docs/books/jls/third_edition/html/binaryComp.html#13.4.9] | ]]></ac:plain-text-body></ac:structured-macro> |
|
| §4§13.124.49, " |
...
...
01. Declarations and Initialization (DCL) DCL05-J. Declare all enhanced for statement loop variables to be final