Java Reference
In-Depth Information
145
Q UALITY T IP 4.1: Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code without
explanation. For example, consider the following scary example that actually
occurs in the Java library source:
h = 31 * h + ch;
Why 31? The number of days in January? One less than the number of bits in an
integer? Actually, this code computes a Ȓhash codeȓ from a stringȌa number that
is derived from the characters in such a way that different strings are likely to yield
different hash codes. The value 31 turns out to scramble the character values nicely.
A better solution is to use a named constant:
final int HASH_MULTIPLIER = 31;
h = HASH_MULTIPLIER * h + ch;
You should never use magic numbers in your code. Any number that is not
completely self-explanatory should be declared as a named constant. Even the
most reasonable cosmic constant is going to change one day. You think there are
365 days in a year? Your customers on Mars are going to be pretty unhappy about
your silly prejudice. Make a constant
final int DAYS_PER_YEAR = 365;
By the way, the device
final int THREE_HUNDRED_AND_SIXTY_FIVE = 365;
is counterproductive and frowned upon.
Q UALITY T IP 4.2: Choose Descriptive Variable Names
In algebra, variable names are usually just one letter long, such as p or A, maybe
with a subscript such as p 1 . You might be tempted to save yourself a lot of typing
by using short variable names in your Java programs:
payment = d + q * QV + di * DIV + n * NV + p * PV;
Search WWH ::




Custom Search