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 Guideline 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 guideline OBJ03-J. Do not use public static non-final variables. Disregarding this advice can expose the constants to pernicious thread safety issues.
Wiki Markup |
---|
At the same time, the use of {{static-final}} modifiers should not be abused. According to the Java Language Specification \[[JLS 2005|AA. Java References#JLS 05]\], sectionSection 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
andfinal
. If the read-only nature offinal
is required, a better choice is to declare aprivate static
variable and a suitable accessor method to get its value.
Furthermore, when read only access is required, it recommends the following:
Code Block |
---|
private static int N; public static int getN() { return N; } |
instead of:
Code Block |
---|
public static final int N = ...; |
Another pitfall arises when static-final
is inappropriately used to declare mutable data. (See guideline OBJ01-J. Be aware that a final reference may not always refer to immutable data.) .
Noncompliant Code Example
...
Wiki Markup |
---|
*EX1*: According to the Java Language Specification \[[JLS 2005|AA. Java References#JLS 05]\], sectionSection 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 lead to thread safety issues as well as inconsistent behavior.
Rule Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL04- J | low | probable | high | P2 | L3 |
...