TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

What is a magic number, and why is it bad?

31 pointsby carlosggover 11 years ago

10 comments

bicxover 11 years ago
I just have a Numbers class I import into all my projects:<p>public final static int ZERO = 0; public final static int ONE = 1; public final static int TWO = 2; public final static int THREE = 3; public final static int FOUR = 4; ....<p>(jk)
评论 #6290938 未加载
评论 #6291045 未加载
评论 #6290711 未加载
radio4fanover 11 years ago
The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant.<p>This also simplifies modifying the program, should the value of pi change.<p>-- Early FORTRAN manual for Xerox Computers
dllthomasover 11 years ago
No one seems to be mentioning another use of the phrase &quot;magic number&quot; which isn&#x27;t bad at all - numbers put in files to mark the file type. 0xCAFEBABE in java class files, for instance.
评论 #6291149 未加载
bluedinoover 11 years ago
That is about the worst top-rated answer I&#x27;ve seen in a while on SO.
评论 #6290714 未加载
评论 #6290571 未加载
nicholassmithover 11 years ago
I&#x27;d have personally thought the number used in the fast inverse square root (<a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="nofollow">http:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root</a>) would qualify as a &#x27;magic number&#x27;, everything else is just a hardcoded value.
timje1over 11 years ago
I find these a lot with CSS - banishing them seem to be a major goal of LESS, SASS etc.<p>They also seem to crop up too often in JS &#x2F; JQuery, particularly the manipulation of CSS.. where do you folks tend to find them?
dsegoover 11 years ago
Also, it can be a good idea to yank out all of those into a separate config file. Although, it destroys locality, so it depends on the use case I guess.
评论 #6294584 未加载
prezjordanover 11 years ago
New term added to my vocabulary - thanks for sharing!
tzsover 11 years ago
I just call any constants that slip into my code &quot;advanced technology numbers&quot; if someone gives me a hard time about them.
a3voicesover 11 years ago
Caring about magic numbers is a distraction from real problems, such as getting your software working.
评论 #6290692 未加载
评论 #6290858 未加载
评论 #6290536 未加载
评论 #6290870 未加载
评论 #6290560 未加载
评论 #6290679 未加载
评论 #6290582 未加载