Monday, 17 July 2017

Code Coverage | What is a magic number?

A magic number is a direct usage of a number in the code.

The term magic number also refers to the bad programming practice of using numbers directly in source code without explanation. In most cases, this makes programs harder to read, understand, and maintain. Although most guides make an exception for the numbers zero and one, it is a good idea to define all other numbers in code as named constants.

Why should it be avoided?
public class Foo {
     public void setPassword(String password) {

           // don't do this
           if (password.length() > 7) {
                throw new InvalidArgumentException("password");
           }
     }
}
Imagine the case where you set the size of the password field in the GUI. If you use a magic number, whenever the max size changes, you have to change in two code locations. If I forget one, this will lead to inconsistencies.

This should be refactored to:
public class Foo {
     // It can be defined in an Interface which used to maintain the constant values.
     public static final int MAX_PASSWORD_SIZE = 7;

     public void setPassword(String password) {
           // This is good to use static final instead of number directy.
           if (password.length() > MAX_PASSWORD_SIZE) {
                throw new InvalidArgumentException("password");
           }
     }
}
It improves readability of the code and it's easier to maintain.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...