...
Another pitfall arises when static-final
is inappropriately used to declare mutable data. (See OBJ03-J. Be aware that a final reference may not always refer to immutable data).
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
.
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
private static final BigDecimal googol = BigDecimal.TEN.pow(100); public static BigDecimal getGoogol() { return googol; } |
Exceptions
Wiki Markup |
---|
*DCL31-J: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." |
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 |
---|---|---|---|---|---|
DCL31- 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
TODO
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" |
...