[kforge-dev] named constants, magic values

John Bywater john.bywater at appropriatesoftwarefoundation.org
Sun Dec 10 21:50:13 UTC 2006


 From a recent commit message:

<quote>I am not entirely clear what the benefit of these type of changes 
are -- i.e. using DB_TYPE instead of 'db.type'? What does this extra 
layer of indirection provide to compensate for the extra 
indirection?</quote>

If the question is, what do named constants provide? the answer is that 
named constants provide maintainability due to compile time checking.

The 'types of changes' that change magic values into named constants 
provide the benefit of having more named constants, therefore more 
maintainable code, and therefore progress the code. (OTOH to revert such 
changes would be to regress the code.)

As there isn't any indirection involved in magic values before named 
constants are introduced, there isn't any extra indirection to be 
compensated for.

I included some more text about named constants and magic values below.

Bye for now,

John.

PS Please note that there is no intention to use named constants for 
print statements (such as logging).


############
For Java, from:
http://www.cs.ucc.ie/~dgb/courses/swd/style/variables.html

Everything that has been said above about magic numbers and the use of 
named constants applies equally well to other values, especially 
strings. On the whole, you should avoid magic strings hard-coded into 
your programs. Instead, use a named constant. A good example of this was 
in the Time class, which used the following named constants:

private static final String MORNING_TEXT = "a.m.";
private static final String AFTERNOON_TEXT = "p.m.";

The program can print times such as "10:30 a.m.". But it is easily 
changed so that it can print "10:30 am" or "10:30 in the morning": we 
simply alter the value of the MORNING_TEXT variable. Converting software 
to a market whose customers speak a language other than English may be 
easier too.

However, it has to be said that most programmers wouldn't take this idea 
too far. Most print statements in a program would still be hard-coded 
strings rather than named constants.

(It might be worth noting, by way of a postscript to this section, that 
using named constants in Java does not worsen run-time efficiency. The 
compiler replaces your constant identifier with the actual value at 
compile-time.)

############
For C, from:
http://willow.engr.uconn.edu/~ldm/cse258/CSE258/coding.html

While it's easy to just hard code them in, it makes the program hard to 
maintain and understand. Instead, all "magic" values must be assigned to 
constants and the constants used exclusively.







More information about the kforge-dev mailing list