...
Another pitfall arises when static-final
is used inappropriately to declare mutable data. (See guideline OBJ01-J. Do not assume that declaring a reference to be final causes the referenced object to be immutable.)
Noncompliant Code Example
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 | ||
---|---|---|
| ||
public BigDecimal googol = BigDecimal.TEN.pow(100); // mathematical constant |
Compliant Solution
To be compliant, ensure that all mathematical constants are declared as static-final
.
...
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. Do not assume that declaring a reference to be final causes the referenced object to be immutable 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." |
DCL04-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 to inconsistent behavior.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL04-J | low | probable | high | 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" |
...