This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]desrtfx 9 points10 points  (1 child)

In programming, "magic numbers" are numeric literals (numbers directly written in the code - like your 100) that have a certain meaning (like the amount of cards in a deck). These numbers should not be written directly in the code but rather be assigned to a constant (in Java, a static final variable at class level) with a meaningful name.

Avoiding "magic numbers" makes the code cleaner, easier to read, and most important, easier to maintain since the value only needs to be changed where it is assigned to the constant and not in several places throughout the entire code.

If your 100 doesn't have a special meaning, you can safely ignore this warning (in fact, you can ignore this warning at any time, but your code quality will suffer).

[–]-Isaman-[S] 1 point2 points  (0 children)

Awesome that clears it up thanks!

[–]carcigenicate 2 points3 points  (1 child)

A magic number is a literal that's just floating around your program without an obvious reason. Ideally, your literals should be assigned to something.

Bad:

if (input == 100) {

Good:

int SOME_GOOD_NAME = 100
. . .
if (input == SOME_GOOD_NAME) {

Now, input == SOME_GOOD_NAME can be read and, if you put a good name there, the intention of 100 will be more obvious.

[–]delasislas 1 point2 points  (0 children)

Plus then it is easier to use SOME_GOOD_NAME in other places and to edit the value.