Question

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?

Was it helpful?

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?

OTHER TIPS

It means when you use numbers in your code (other than -1, 0 and 1) that you use a constant to "label" it.

Ie instead of:

boolean pass = score >= 50;

Use this:

private static final int MINIMUM_PASS_SCORE = 50;

boolean pass = score >= MINIMUM_PASS_SCORE;

I believe it means to use them without defining what they actually are. For example instead of stating:

public static double PI = 3.14; //<-- Clearly defines the meaning of this value.

you're just using the decimal value.

double a = Math.pow(3.14 * r, 2); // <-- Does not define the meaning of 3.14

This makes code harder to read, and therefore is an avoided practise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top