Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckStyle with warning '100' is a magic number

In my code,it shows the warning with message '100' is a magic number.See the below code,

int randomNo = generator.nextInt(100);

I read it here What is a magic number, and why is it bad? but my doubt is declaring 100 by creating variable with static will occupy more space,since i am using this in a single place.Is this a correct way to solve this?

  public static final int HUNDRED= 100;

Any Suggestion?

like image 425
mohammed sameen Avatar asked May 05 '15 05:05

mohammed sameen


1 Answers

Check out Robert Martin's (Uncle Bob)

Clean Code

book for a thorough explanaition (or any other guide on coding style). Basically a hard coded '100' doesn't mean anything to the reader of your code. It won't mean anything to you in 6 months either, after you are done with your app. It is a magic number since it appears in the code - in 99 out of 100 cases - as almost out of nowhere. Why is it 100 and not 99 or 101? Why should your app limit the random number generation to 100 and not above (or below)?

To wrap up, it's a thing of readability of your code for yourself and for present or future readers of your code, it's a matter of coding style.

like image 159
ttarczynski Avatar answered Oct 07 '22 11:10

ttarczynski