Search code examples
javaconventions

Java code convention clarification - directly coding numerical constants


In the Java Code Conventions, section 10.3 it states:

Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.

What does it mean to 'code directly' numerical constants?


Solution

  • It refers to so called "magic numbers". Observe the following code:

    float radians = 180/3.141;
    

    versus

    float degreesInRadians = myDegrees/Math.PI;
    

    Which one is clearer?