Java Reference
In-Depth Information
Compliant Solution
Thiscompliantsolutionusestheidentifierassignedtotheconstantvalueintheexpression:
Click here to view code image
private static final int BUFSIZE = 512;
// ...
public void shiftBlock(int nbytes) {
int nblocks = 1 + (nbytes - 1) / BUFSIZE;
// ...
}
Applicability
Using numeric literals makes code more difficult to read, understand, and edit.
The use of symbolic constants should be restricted to cases in which 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, using symbolic constants can impair code read-
ability. The following code example obscures the meaning of the code by using too many
symbolic constants.
Click here to view code image
private static final double FOUR = 4.0;
private static final double THREE = 3.0;
double volume(double radius) {
return FOUR / THREE * Math.PI * radius * radius * radius;
}
The values 4.0 and 3.0 in the volume calculation are clearly scaling factors used to
calculate the sphere's volume and are not subject to change (unlike the approximate value
for π), so they can be represented exactly. There is no reason to change them to increase
precision because replacing them with symbolic constants actually impairs the readability
of the code.
Bibliography
[Core Java 2003]
Search WWH ::




Custom Search