Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

A related error can arise when a programmer declares a static final reference to a mutable object; see guideline OBJ01-J. Do not assume that declaring a reference to be final causes the referenced object to be immutable for additional information.

Noncompliant Code Example

In this noncompliant code example, class Foo declares a field whose value represents the version of the software. The field is subsequently accessed by class Bar, which lives in a separate compilation unit.

...

Although recompiling Bar.java will solve this problem, a better solution is available.

Compliant Solution

Wiki Markup
According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 13.4.9, "{{final}} Fields and Constants"

...

The private version value can therefore not be copied into the Bar class when it is compiled, thus preventing the bug. Note that most JITs are capable of inlining the getVersion() method at runtime; consequently there is little or no performance penalty incurred.

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-EX3: Constants whose value never changes throughout the entire lifetime of the software may be declared as 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"

...