...
Code Block | ||
---|---|---|
| ||
double area(double radius) { return 4.0 * Math.PI * radius * radius; } double volume(double radius) { return 4.0/3.0 * Math.PI * radius * radius * radius; } double greatCircleCircumference(double radius) { return 2 * Math.PI * radius; } |
Noncompliant Code Example
This noncompliant code example defines a constant BUFSIZE
, but then defeats the purpose of defining BUFSIZE
as a constant by assuming a specific value for BUFSIZE
in the following expression:
Code Block | ||
---|---|---|
| ||
private final int BUFSIZE = 512;
// ...
nblocks = 1 + ((nbytes - 1) >> 9); /* BUFSIZE = 512 = 2^9 */
|
The programmer has assumed that it is obvious that BUFSIZE
is 512, and right-shifting 9 bits is the same (for positive numbers) as dividing by 512. However, if BUFSIZE
changes to 1024 in the future, modifications will be both difficult and error prone.
Compliant Solution
This compliant solution uses the identifier assigned to the constant value in the expression.
Code Block | ||
---|---|---|
| ||
nblocks = 1 + (nbytes - 1) / BUFSIZE;
|
Exceptions
DCL02-EX1: The use of symbolic constants should be restricted to cases where they improve the readability and maintainability of the code. When the intent of the literal is obvious, or where the literal is not likely to change, use of symbolic constants can impair code readability. The following noncompliant code example obscures the meaning of the code by using too many symbolic constants.
...