Versions Compared

Key

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

...

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 recommends the followingThat is, the JLS recommends this:

Code Block
private static int N;
public static int getN() { return N; }

instead of:

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

...

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.

...

bgColor#ccccff

...

Note that the variable googol is actually a static final reference to an object of type BigDecimal. Because instances of BigDecimal are immutable, guideline OBJ01-J. Be aware that a final reference may not always refer to immutable data is irrelevant in this case.

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."

...

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

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

DCL04-J

low

probable

high

P2

L3

Automated Detection

TODOStatic 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.

...