Still a magic number?
So Sam and I were programming today, and we found a place in the code where we were using a magic number. Something along the lines of:
function TMyObject.IsEditable: Boolean; begin Result := obj.IsEditable(1); end;
Wanting to replace the magic number with a meaninful symbolic constant, we looked around for what the magic number could represent. After failing to find what exactly the magic number meant, and not wanting to leave a magic number in the code, we replaced it with our own meaningful constant. The code now looks more like this:
function TMyObject.IsEditable: Boolean; const MagicNumber = 1; begin Result := obj.IsEditable(MagicNumber); end;
So, if we replace a magic number with a poorly named constant, is it still considered a magic number?
September 8th, 2005 at 8:36 am
Yes.
A magic number is one that you don’t know what it means, why you have to have it, how it works, what would happen if you change it, or the conditions when you *should* change it. It’s just magic.
Giving it it’s own constant doesn’t de-shroud the mystery any, so it’s still a magic number until you give it a *meaningful* name.
OTOH, this is progress because the code now acknowledges that it doesn’t know what the number is, and you have a good place to record the info once you find it. So this refactoring is a small step in the right direction.
September 8th, 2005 at 6:41 pm
Yeah, I realize that this is not the correct fix, but as you said, it does make it more obvious that it is a magic number.
June 15th, 2006 at 12:20 am
This Information is really very good