Java Reference
In-Depth Information
return 4.0 / 3.0 * 3.14 * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * 3.14 * radius;
}
The code uses the literal
3.14
to represent the value π. Although it removes some of
the ambiguity from the literals, it complicates code maintenance. If the programmer were
to decide that a more precise value of π is desired, all occurrences of
3.14
in the code
would have to be found and replaced.
Compliant Solution (Constants)
In this compliant solution, a constant
PI
is declared and initialized to
3.14
. Thereafter, it
is referenced in the code whenever the value of π is needed.
private static final double PI = 3.14;
double area(double radius) {
return PI * radius * radius;
}
double volume(double radius) {
return 4.0/3.0 * PI * radius * radius * radius;
}
double greatCircleCircumference(double radius) {
return 2 * PI * radius;
}
This technique reduces clutter and promotes maintainability. If a more precise approx-
imation of the value of π is required, the programmer can simply redefine the constant.
Theuseoftheliterals
4.0
,
3.0
,and
2
doesnotviolatethisguideline,forreasonsexplained
in the “Applicability” section of this guideline.
Compliant Solution (Predefined Constants)
Use predefined constants when they are available. The class
java.lang.Math
defines a
large group of numeric constants, including
PI
and the exponential constant
E
.