Over the last couple of months I have been diving into coding standard IfSQ. As a part of this IfSQ standard, a rule is to not use
Magic Numbers. While I don't have a problem with building this rule into checks as FxCop or StyleCop, I am confused as to what actually IS a Magic Number.
According to Wikipedia there are 3 explanations of magic numbers:
- A constant numerical or text value used to identify a file format or protocol;
- Distinctive unique values that are unlikely to be mistaken for other meanings (e.g., Globally Unique Identifiers);
- Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants.
I am focussing on the third meaning. But this is also where I am stuck. Seeing as I am trying to build this in a FxCop rule; the check has to be automated. But what am I supposed flag as magic number?
The IfSQ standard explains the following as magic numbers:
Numeric literals (other than 0 or 1) have been embedded directly into the source code. For example "34" or "86400".
But this doesn't sound good to me at all. This would mean I'd have to flag every single occurence of a number other than 0 and 1. Numbers like 24 (hours), 60 (minutes) and 100 (percentage) are, in their correct context, no magic numbers; in my eyes that is.
Because this is will be an automated check, looking from things in a contextual way isn't really possible.
Based on this I have the following questions:
- How should I define a magic number?
- Is it possible to define magic numbers without context?
- Should I skip certain statements when checking for magic numbers?