Versions Compared

Key

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

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 value of any public final 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 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).

Noncompliant Code Example

In this noncompliant code example, class Foo in Foo.java declares a field whose value represents the version of the software:

Code Block
bgColor#ffcccc
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
bgColor#ffcccc
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

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
    You are using version 1

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 JLS [JLS 2013],

Literals that describe mathematical constants are often used to represent well established constants. This eliminates the need to use their actual values throughout the source code and reduces the possibility of committing frivolous errors. (See DCL02-J. Use meaningful symbolic constants to represent literal values in program logic for more information)

If a mathematical constant is not declared static, every instance of the class object will needlessly retain its own copy of the constant. Moreover, failing to declare a constant field final can be counterproductive as highlighted in OBJ03-J. Do not use public static non-final variables. Disregarding this advice can expose the constants to pernicious thread safety issues.

Wiki MarkupAt the same time, the use of {{static-final}} modifiers should not be abused. According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\] section 13.4.9 "{{final}} Fields and Constants":

Other than for true mathematical constants, we recommend that source code make very sparing use of class variables that are declared static and final. If the read-only nature of final is required, a better choice is to declare a private static variable and a suitable accessor method to get its value.

Furthermore, when read only access is required, it recommendsIn this compliant solution, the version field in Foo.java is declared private static and accessed by the getVersion() method:

Code Block
bgColor#ccccff
class Foo {
  private static int version = N1;
  public static final int getNgetVersion() {
    return Nversion;
  }

instead of:

Code Block
public static final int N = // ...;

Another pitfall arises when static-final is inappropriately used to declare mutable data. (See OBJ01-J. Be aware that a final reference may not always refer to immutable data).

Noncompliant Code Example


}

The Bar class in Bar.java is modified to invoke the getVersion() accessor method to retrieve the version field from Foo.java:This noncompliant code example does not qualify the constant value googol (10 raised to the power 100) with the static and final modifiers.

Code Block
bgColor#ffcccc#ccccff
class Bar {
  public BigDecimalstatic googol = BigDecimal.TEN.pow(100); // mathematical constant

Compliant Solution

To be compliant, ensure that all mathematical constants are declared as static-final.

Code Block
bgColor#ccccff

public static final BigDecimal googol = BigDecimal.TEN.pow(100);

Compliant Solution

This compliant solution ensures that all mathematical constants are declared as static-final. Additionally, it provides read-only access to the constant by reducing its accessibility to private and providing an accessor method.

Code Block
bgColor#ccccff

private static final BigDecimal googol = BigDecimal.TEN.pow(100);
public static BigDecimal getGoogol() { return googol; }

Exceptions

Wiki Markup
*EX1*: According to the Java Language Specification \[[JLS 05|AA. Java References#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."

EX2: Constants declared using the enum type may violate this guideline.

Risk Assessment

Failing to declare mathematical constants static and final can lead to thread safety issues as well as inconsistent behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL04- J

low

probable

high

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C Secure Coding Standard as DCL00-C. Const-qualify immutable objects.

References

Wiki Markup
\[[JLS 05|AA. Java References#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"

void main(String[] args) {
    System.out.println(
      "You are using version " + Foo.getVersion());
  }
}

In 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 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 final. For instance, the JLS recommends that mathematical constants be declared final.

Bibliography

 

...

Image Added Image Added Image AddedDCL03-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