...
The final
keyword in Java is used to declare constants. Its effect is to render the affected non-composite variable immutable. Attempting to change the value of a final
-qualified variable results in a compile-time error. As constants cannot be changed, it is desirable to define only one instance of them for the class; consequently constants should also be declared with the static
modifier. (See guideline DCL04-J. Declare mathematical constants as static and final.)
The following code fragment demonstrates the use of static
and final
to create a constant:
...
Although final
is most often safe for creating compile time immutable constants, its use has a few caveats when dealing with composite objects (mutable data in particular). See guideline OBJ01-J. Be aware that a final reference may not always refer to immutable data for more details.
...
Using numeric literals makes code more difficult to read, understand and edit.
Recommendation Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL02- J | low | unlikely | high | P1 | L3 |
...
This rule appears in the C++ Secure Coding Standard as DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic and .
This rule also appears in the C Secure Coding Standard as DCL06-C. Use meaningful symbolic constants to represent literal values in program logic.
...