When Check Style warns you about a magic number in your code

When Check Style warns you about a \"magic number\" in your code, what does this mean? Explain briefly why this warning is something you, as a software professional, should pay attention to and consider fixing

Solution

When CheckStyle warns about having a \"magic number\" in the code, it means that there is a numeric literal used in the code which is not defined as a variable.

Say for example, I am developing an application in which I am declaring an array as: int a[] = new int[10];

This may display a warning saying \"10 is a magic number\" or something like that. This means that I have used numeric literal 10 in my code and I should have declared it as const variable using final keyword.

Note: In the definition of magic number, it is written that -1, 0, 1 and 2 are not magic numbers. So, if you use them like i = i + 1 it won\'t display such warning of magic number.

This is just a warning, so leaving it as it is would be fine, but being a good software professional, I should be solving this. This is helpful for easiness and readability purpose mainly. For an instance, let\'s say I wrote the above array declaration in between the program. If I need to change its size, then I need to go to that particular line and change it. Or I need to find that value in the code and then change it. What if several times 100 is written in my code, I need to go through every such line to reach my desired line. What if the desired line is after 1000 lines of code. It becomes not so easy for a developer when such condition arises. So, if I just declare it in the top of the file as a constant, like: public static final MYARRAY_DIM = 100. So, after that I do not need to search for that line as previous to modify this value. I can do it easily as this line is written at the top so going there and changing it becomes so easy task.

This also helps in increasing the readability of your code. If some other professional sees your code, he/she can easily come to know that the constant defined as above is holding the array dimension value. So, in this way also solving the magic number warning helps.

This is what I can give input on the thing. Do comment if there is any query, I will help with it for sure. Thank you. :)

 When Check Style warns you about a \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site