This is somewhat controversial topic, and I guess there is as many opinions as there are programmers. But for the sake of it, I want to know what are the common practices in business (or in your work places).
In my work place we have a strict coding guidelines. One section of that is dedicated to magic strings/numbers. It states (for C#):
Do not use literal values, either numeric or strings, in your code other than to define symbolic constants. Use the following pattern to define constants:
public class Whatever { public static readonly Color PapayaWhip = new Color(0xFFEFD5); public const int MaxNumberOfWheels = 18; }
There are exceptions: the values 0, 1 and null can nearly always be used safely. Very often the values 2 and -1 are OK as well. Strings intended for logging or tracing are exempt from this rule. Literals are allowed when their meaning is clear from the context, and not subject to future changes.
mean = (a + b) / 2; // okay
WaitMilliseconds(waitTimeInSeconds * 1000); // clear enough
An ideal situation would be some official research paper showing effects on readability/maintainability of the code when:
- Magic numbers/strings are all over the place
- Magic strings/numbers are replaced by constant declarations reasonably (or in different degrees of coverage) - and please don't shout at me for using "reasonably", I know everyone has different idea what "reasonably" is
- Magic strings/numbers arereplaced in excess and in places where they wouldn't have to be (see my example below)
I would like to do this to have some scientificaly-based arguments when arguing with one of my collegues, who is going to the point of declaring constants like:
private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;
Another example would be (and this one is in JavaScript):
var someNumericDisplay = new NumericDisplay("#Div_ID_Here");
Do you stick DOM IDs on top of your javascript file if that ID is used only in 1 place?
I have read the following topics:
StackExchange
StackOverflow
Bytes IT Community
There is many more articles, and after reading these some patterns emerge.
So my question is should be using magic strings and numbers in our code? I am specifically looking for expert answers that are backed by references if possible.
NumberTen = 10
That is pointless as the number 10 will not be redefined.MaxRetryCount = 10
That has a point a we may want to change the max retry count.private const char SemiColon = ';';
Dumb.private const char LineTerminator = ';'
; Smart.