Filed under: Clean code, — Tags: Magic number, Magic numbers, Readability — Thomas Sundberg — 2011-07-28
The other day a colleague asked me, what is a magic number? He had noticed that one of the things our Sonar was complaining about was Magic numbers. I got a great teaching moment and told him my view of Magic numbers.
Magic numbers are any numbers in the source code that just appears without any explanation.
An example, create a buss and some of it's properties:
Bus bus = new Bus(12, 53);
Just by watching the statement above, you cannot clearly know what each parameter stands for. If I rewrite the code somewhat like this:
Bus bus = new Bus(12, 53); // length, passengers
It gets a little bit easier to understand what the parameters stands for.
But writing a comment like this can be avoided. Instead of writing a comment, create two variables with good names and use them instead. Another rewrite and the code could look like this:
int length = 12; int passengers = 53; Bus bus = new Bus(length, passengers);
It is now clear when you look at the code what each of the two parameters stands for. The advantage of using two variables instead of a comment is that the comment may or may not be updated when the code is maintained. Changing the name of a variable is more likely to happen than that somebody updates a comment. Comments tend to grow old and obsolete, variables tend to be maintained better.
The disadvantage of adding the two variables are that the code gets longer. It is three times longer in the example above. My opinion though is that two added lines is a very small price to pay for increased readability and maintainability.