Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor grammar changes

...

The class java.lang.Math defines a large set group of numeric constants, including PI and the exponential constant E. Prefer the use of predefined constants when they are available.

...

DCL02-EX1: The use of symbolic constants should be restricted to cases where they improve the readability and maintainability of the code. Using them when 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 takes this rule too farobscures the meaning of the code by using too many symbolic constants.

Code Block
bgColor#ffcccc
private static final double AREA_FACTOR = 4.0 * Math.PI;
private static final double VOLUME_FACTOR = 4.0/3.0 * Math.PI;
private static final double CIRCUMFERENCE_FACTOR = 2.0 * Math.PI;

double area(double radius) {
  return AREA_FACTOR * radius * radius;
}

double volume(double radius) {
  return VOLUMNE_FACTOR * radius * radius * radius;
}

double greatCircleCircumference(double radius) {
  return CIRCUMFERENCE_FACTOR * radius;
}

The values 4.0 and 3.0 in the volume calculation are clearly scaling factors used to calculate the circle sphere's volume and are not subject to change (unlike the approximate value for pi), so they can be represented exactly; there is no reason to change them to increase precision. Hence, replacing them with symbolic constants is overkill, and renders impairs the readability of the code less readable.

Risk Assessment

Using numeric literals makes code more difficult to read, understand, and edit.

...