hey all.
i lost .5 marks in my assignmenta t uni for "using magic numbers, which you shoudln't"
i have no idea what these are. is this a java term?
Printable View
hey all.
i lost .5 marks in my assignmenta t uni for "using magic numbers, which you shoudln't"
i have no idea what these are. is this a java term?
It's quite a general term: Magic number (programming) - Wikipedia, the free encyclopedia (You probably offended against 2: Unnamed numerical constants)
Here, 5 and 10 are considered magic numbers. Why are they bad? What happens if the length of the array changes? Suddenly the loop breaks. What if the value 10 is scattered 1000 times across a 1000000 line program? You would have to hunt down and change every instance instead of using a variable that can be changed once.Code:int[] values = {1,2,3,4,5};
for(int index = 0; index < 5; index++) {
System.out.println(values[index] / 10);
}
Code:final int DIV = 10;
int[] values = {1,2,3,4,5};
for(int index = 0; index < values.length; index++) {
System.out.println(values[index] / DIV);
}
i probably did.
the line above was
if(args.length == 3){
maybe that's what is wrong
i did this because it MUST have 3 args, it also said i can assume they will enter the correct values :P
what should've i done? if checking if the length is 3 ?
You should have used a variable and assigned the value 3 to it. In future if the requirements of the program changed to be more or less than 3 arguments then it is easier to find the variable declared at the top of your code than hunting through the body of the code to make the change. It is only a minor problem and hence you only lost a half a mark.
This is the lovely part of having teachers who were not born to teach.
I use magic numbers sometimes though, I mean, it kind of depends on the usage. I see no point in doing this:
...when I could do this:Code:int x = 5;
if (someOtherVar == x) ...
Code:if (someOtherCar == 5) ...
Why would I waste the time to type it out, the memory to allocate it, and the storage to save it? If the variable has no other outside factors and is completely static in context, it needs no variable storage.
[/rant]
exactly what i was thinking :D
Rubble rubble rubble
For the very reasons already stated. What happens if the 5 gets changed to 6. It is much easier if you use a variable declared at the top of the class. Or even better use a Properties object.
i swing both ways here.
i think it's easier just typing the 5 BUT at the same time i think it's better practice to use variables /properties
The wikipedia article I linked to discusses "accepted usage" which "is subjective, and often depends on individual coding habits"
They give these examples:
Code:for (int i = [b]0[/b]; i < max; i = i + [b]1[/b]) //assuming i++ is not supported
isEven = (x % [b]2[/b] == 0); // Is zero magic?
circumference = [b]2[/b] * Math.PI * radius
Regarding the last one, at least Math.PI is nonmagic! Things will be easy to change if ever pi were to change its value...