Thomas Sundberg

July 28, 2011

Magic numbers

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.

Resources

About these ads

12 Comments »

  1. Great teaching! Thanks!

    Comment by David — April 27, 2012 @ 16:44

  2. Thanks…That really Helped.
    Cheers !!!

    Comment by Nilesh — July 3, 2012 @ 04:55

  3. I have declared one variable like,
    private volatile int refreshInterval = 60000;

    And this throws as ‘60000’ is a magic number.

    Comment by Sunil — August 8, 2012 @ 14:45

    • Hi!

      I tried the same thing using Java and cant reproduce an exception that states that ‘60000’ is a magic number.

      I also claim that what you show here is not a magic number. It is defined as the variable ‘refreshInterval’ and therefore not a magic number.

      /Thomas

      Comment by Thomas Sundberg — August 15, 2012 @ 06:18

    • Try making it const

      Comment by roynitert — October 21, 2012 @ 16:39

      • A const is good. Just a variable is often enough to make sure it is described enough and therefore not a magic number anymore.

        /Thomas

        Comment by Thomas Sundberg — October 21, 2012 @ 20:02

      • The tooling I use will keep complaining it is a magic number until I make it const. I think it is better to use const. Consider this code just using variables:
        double pi = 3.141592653;
        …..
        pi = pi + 5; // Why would someone do this ?
        …..
        double area = pi * r ^ 2;

        Making pi const prevents any changes to it from the definition to its use.

        Uncle Bob mentions this in his book “clean code” in chapter 17 on smells and heuristics: G25 Replace Magic Numbers with Named Constants

        Comment by Roy Nitert — October 22, 2012 @ 07:22

      • Well, I would say that it depends. In some cases a const is definitely the way to go. In some other cases it is not. If the value isn’t needed anywhere outside a specific method, why make it a const then?

        Consider this


        @Test
        public void shouldVerifySomething() {
        boolean actual = foo(17);
        assertTrue(actual);
        }

        @Test
        public void shouldAlsoVerifySomething() {
        int someNumber = 17;
        boolean actual = foo(someNumber);
        assertTrue(actual);
        }

        The number 17 is not important for the test for some strange reason. It is just something that actually is needed to call the method. In this case I would probably stop with just a named variable. The method foo() isn’t called anywhere else and therefore I don’t see a good reason for making it a const. If foo() had been called from many tests, I might have considered making it a const. But that decision would depend on how I would value readability v.s. information hiding in this test class. I try to avoid hiding important information, but is someNumber important here? The name suggests that it isn’t.

        In your example, pi is most likely a const and should be treated as such.

        /Thomas

        Comment by Thomas Sundberg — October 22, 2012 @ 07:58

  4. I tend to reason the other way: I don’t see a good reason for not making it a const. You seem to suggest that adding the const keyword will make it less readable? I feel the following code is a bit more readable even.

    @Test
    public void shouldAlsoVerifySomething() {
    const int someNumber = 17;
    boolean actual = foo(someNumber);
    assertTrue(actual);
    }

    But, I agree with you (in another post) that clean code is very subjective. It’s a matter of taste what is more readable.

    Comment by Roy Nitert — October 22, 2012 @ 10:33

    • I guess I am. Does it bring you any additional value using const? If you feel that it does, use it. Otherwise don’t.

      We obviously agree on the important stuff. At this low level I don’t actually think it is very important if you set an irrelevant number as a const or not.

      Another reason why I probably wouldn’t use const is the fact that it is a reserved but not used word i Java. My example above is in Java and JUnit.

      /Thomas

      Comment by Thomas Sundberg — October 22, 2012 @ 10:42

      • Yes, the important stuff being that you give meaning to a number by naming it.

        Ah, it might be a diffence between Java en C++ then. My background is mainly in C, C++, C#. In Java you wouldn’t use const, but you could use final.

        Keep up the good work. I only found your blog yesterday, and still want to read more of your posts. I am especially interested in SW craftsmanship and clean code.

        Comment by roynitert — October 22, 2012 @ 18:04


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Silver is the New Black Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 50 other followers

%d bloggers like this: