When people talk about the use of “magic numbers” in computer programming, what do they mean?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Magic numbers are any number in your code that isn’t immediately obvious to someone with very little knowledge.
For example, the following piece of code:
has a magic number in it and would be far better written as:
Some extreme views state that you should never have any numbers in your code except -1, 0 and 1 but I prefer a somewhat less dogmatic view since I would instantly recognise 24, 1440, 86400, 3.1415, 2.71828 and 1.414 – it all depends on your knowledge.
However, even though I know there are 1440 minutes in a day, I would probably still use a
MINS_PER_DAYidentifier since it makes searching for them that much easier. Whose to say that the capacity increment mentioned above wouldn’t also be 1440 and you end up changing the wrong value? This is especially true for the low numbers: the chance of dual use of 37197 is relatively low, the chance of using 5 for multiple things is pretty high.Use of an identifier means that you wouldn’t have to go through all your 700 source files and change
729to730when the capacity increment changed. You could just change the one line:to:
and recompile the lot.
Contrast this with magic constants which are the result of naive people thinking that just because they remove the actual numbers from their code, they can change:
to:
That adds absolutely zero extra information to your code and is a total waste of time.