Magic Numbers

The term magic number refers to the poor programming practice of using numbers directly in source code without explanation. In most cases this makes programs harder to read, understand, and maintain. Although most guides make an exception for the numbers zero and one, it is a good idea to define all other numbers in code as named constants.

For example, to shuffle the values in an array randomly, this pseudocode will do the job:

for i from 1 to 52
       j := i + randomInt(53 - i) - 1
       a.swapEntries(i, j)

where a is an array object, the function randomInt(x) chooses a random integer between 1 to x, inclusive, and swapEntries(i, j) swaps the ith and jth entries in the array. In this example, 52 is a magic number. It is considered better programming style to write:

constant int deckSize := 52
   for i from 1 to deckSize
       j := i + randomInt(deckSize + 1 - i) - 1
       a.swapEntries(i, j)

Problems with magic numbers

Because magic numbers are of an arbitrary value, they do not often carry a meaning by themselves; in most cases it is up to the documentation of one's code to specify exactly what the magic number represents. Also, magic numbers are not typesafe, that is, one could erroneously add one to another and arrive at a nonsensical result.

Lastly, although highly coincidental, situations arise when numbers may accidentally match magic numbers during comparison operations. It is for these reasons that the use of Enumerated types, or enums, is quickly overtaking the use of magic numbers. Although enums are represented in most languages as an integer, the name of the enum is used rather than the number itself.

page_revision: 1, last_edited: 1250729572|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial 3.0 License