Literals that describe mathematical constants are often employed to represent well established valuesconstants. This eliminates the need to use their actual values throughout the source code and thus reduces the possibility of committing frivolous errors. (See DCL03-J. Use meaningful symbolic constants to represent literal values in program logic for more information)
...
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.
FurtherFurthermore, when read only access is required, it recommends:
Code Block |
---|
private static int N; public static int getN() { return N; } |
rather thaninstead of:
Code Block |
---|
public static final int N = ...; |
...
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 a getter method.
Code Block | ||
---|---|---|
| ||
private static final BigDecimal googol = BigDecimal.TEN.pow(100);
public static BigDecimal getGoogol() { return googol; }
|
Exceptions
DCL31-J:EX1: According to the JLS "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."
...