Concept

Magic number (programming)

Summary
In computer programming, a magic number is any of the following: A unique value with unexplained meaning or multiple occurrences which could (preferably) be replaced with a named constant A constant numerical or text value used to identify a or protocol; for files, see A distinctive unique value that is unlikely to be mistaken for other meanings (e.g., Globally Unique Identifiers) The term magic number or magic constant refers to the anti-pattern of using numbers directly in source code. This has been referred to as breaking one of the oldest rules of programming, dating back to the COBOL, FORTRAN and PL/1 manuals of the 1960s. The use of unnamed magic numbers in code obscures the developers' intent in choosing that number, increases opportunities for subtle errors (e.g. is every digit correct in 3.14159265358979323846 and is this equal to 3.14159?) and makes it more difficult for the program to be adapted and extended in the future. Replacing all significant magic numbers with named constants (also called explanatory variables) makes programs easier to read, understand and maintain. Names chosen to be meaningful in the context of the program can result in code that is more easily understood by a maintainer who is not the original author (or even by the original author after a period of time). An example of an uninformatively named constant is int SIXTEEN = 16, while int NUMBER_OF_BITS = 16 is more descriptive. The problems associated with magic 'numbers' described above are not limited to numerical types and the term is also applied to other data types where declaring a named constant would be more flexible and communicative. Thus, declaring const string testUserName = "John" is better than several occurrences of the 'magic value' "John" in a test suite. For example, if it is required to randomly shuffle the values in an array representing a standard pack of playing cards, this pseudocode does the job using the Fisher–Yates shuffle algorithm: for i from 1 to 52 j := i + randomInt(53 - i) - 1 a.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.