An issue is raised when a literal numeric value in the code closely matches a well-known mathematical constant (such as π or e), but differs slightly in precision.
Hard-coding approximate values of well-known mathematical constants creates several problems in your codebase.
First, these hard-coded values often lack the full precision available in predefined library constants. For example, writing 3.14
instead of using a library-provided constant for π loses significant decimal places, potentially leading to calculation errors in scientific or
engineering applications.
Second, hard-coded values make your code less readable. When other developers see 3.14159, they must recognize it as π themselves.
Using named constants from standard libraries makes the intent immediately clear.
Third, maintenance becomes harder. If you need to change the precision or update the value across your codebase, you must find and modify multiple literal values. With named constants, the meaning is centralized and clear.
Finally, hard-coded approximations suggest a lack of awareness of standard library features, which can undermine confidence in the code quality.
Common constants that are frequently approximated include:
If a literal value happens to be close to one of these constants but represents something else entirely, such as a version number or a domain-specific threshold, mark the issue as won’t-fix.
In Java, these constants and functions are available in the Math class: Math.PI, Math.E,
Math.sqrt(2), and Math.log(2).
Using hard-coded approximations instead of predefined constants reduces code quality in three main ways:
Replace hard-coded numeric approximations with the appropriate predefined constant from the Math class. For π, use
Math.PI. For Euler’s number, use Math.E. For other common constants that don’t have direct equivalents, use mathematical
expressions like Math.sqrt(2) or Math.log(2).
public class CircleCalculator {
public double calculateArea(double radius) {
return 3.14 * radius * radius; // Noncompliant
}
public double calculateCircumference(double radius) {
return 2 * 3.14159 * radius; // Noncompliant
}
}
public class CircleCalculator {
public double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public double calculateCircumference(double radius) {
return 2 * Math.PI * radius;
}
}