News for hackers. Stuff that matters.
Re:What is a magic number, and why is it bad? by bluedino on Wednesday August 28, 2013 @11:21AM (#6290533)
That is about the worst top-rated answer I've seen in a while on SO.
Re:What is a magic number, and why is it bad? by simias on Wednesday August 28, 2013 @11:46AM (#6290714)
Agreed.

In my opinion there are two kinds of magic numbers:

* the first kind is the one most answers describe: an arbitrary number used in various places that may change at any moment. The size of a buffer for instance.

* the second kind are numbers that represent something very specific but not immediately obvious when reading the code: for instance in a device driver "read_register(base + DEVICE_STATUS)" is much clearer than "read_register(base + 0x3c)". In this case naming the magic number is useful even if it's used only once in the code. It acts as a comment basically.

I'd also add that sometimes adding too many levels of indirection is a bad thing, and in the (currently) top voted answer I prefer the original over the "fixed" version. Either you do the right thing and make MAX_PASSWORD_SIZE something meaningful or you might as well write "if (password.length() > 7)". It's clear, non ambiguous and (in the example) not reused anywhere. Defining a macro for that just hides poor code and forces me to go look for the definition in order to understand what's going on (while debugging for instance).

Re:What is a magic number, and why is it bad? by praptak on Wednesday August 28, 2013 @11:28AM (#6290571)
Agreed. All of the top 3 answers focus on the numbers being directly used in code which is not the real reason why magic numbers cause problems.

They are bad because of not being explained. A number directly used in code is not magic if it is properly commented. Granted, explaining it by making it a named constant is very often better (reusability), but a literal number that is merely commented is not "magic".