Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

language agnostic - What are "magic numbers" in computer programming?

When people talk about the use of "magic numbers" in computer programming, what do they mean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

sz = sz + 729;

has a magic number in it and would be far better written as:

sz = sz + CAPACITY_INCREMENT;

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_DAY identifier 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 729 to 730 when the capacity increment changed. You could just change the one line:

#define CAPACITY_INCREMENT 729

to:

#define CAPACITY_INCREMENT 730

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:

x = x + 4;

to:

#define FOUR 4
x = x + FOUR;

That adds absolutely zero extra information to your code and is a total waste of time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...