...
This both clarifies the code and allows easy editing, for if a different value for pi is required, the programmer can simply redefine the constant.
Exceptions
The use of symbolic constants should be restricted to cases where they improve the readability and maintainability of the code. Using them when the intent of the literal is obvious, or where the literal is not likely to change, can impair code readability. In the Compliant Solution above, the values 4.0 and 3.0 in the volume calculation are clearly scaling factors used to calculate the circle volume, and as such are not subject to change (unlike pi, they can be represented exactly, so there is no reason to change them to increase precision). Hence, replacing them with symbolic constants would be inappropriate.
Risk Assessment
Using numeric literals makes code more difficult to read, understand or edit.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
X | low | unlikely | high | P1 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C++ Secure Coding Standard as DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic and in the C Secure Coding Standard as DCL06-C. Use meaningful symbolic constants to represent literal values in program logic.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\]
\[[Core Java 04|AA. Java References#Core Java 04]\] |