...
Constants should be declared as static
and final
. For example:,
Code Block |
---|
private static final int SIZE = 25; |
...
The methods use the seemingly arbitrary literals 3.14
, 4.19
, and 6.28
to represent various scaling factors used to calculate these dimensions. A developer or maintainer reading this code would have little idea about how they were generated or what they mean and consequently would be unable to not understand the function of this code.
...
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 π
of π is needed.
Code Block | ||
---|---|---|
| ||
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 approximation of the value of π
of π is required, the programmer can simply redefine the constant.
...
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.
...
...