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 OBJ50-JG. Never confuse immutability of a reference with that of the referenced object 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 from a separate compilation unit.

...

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

Compliant Solution

According to §13.4.9, "final Fields and Constants," of the Java Language Specification [JLS 2011],

...

In this solution, the private version value cannot be copied into the Bar class when it is compiled, consequently preventing the bug. Note that most just-in-time (JIT) code generators can inline the getVersion() method at runtime, so little or no performance penalty is incurred.

Applicability

Declaring as final a value that changes over the lifetime of the software may lead to unexpected results.

...

Constants whose value never changes throughout the entire lifetime of the software may be declared as final. For instance, the Java Language Specification recommends that mathematical constants be declared final.

Bibliography

...