Magic numbers are bad... I totally agree. But there's one magic number I find hard to fix:
'100' is a magic number.
Consider this code:
public double getPercent(double rate) {
return rate * 100;
}
public double getRate(double percent) {
return percent / 100;
}
SonarQube will raise 2 violations, one for each use of 100. I could replace 100 with a constant variable, but what would be a good name for it? Is that really a good idea? If somebody ever changes its value that will be a disaster. I could also just add // NOSONAR
to all the lines that use 100.
What is the best practice for dealing with the magic number 100?
UPDATE
From the answers, the most useful bit for me was this:
Practical Magic Number rule: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal.
So by this logic, 100 is NOT a magic number.
However, to make the violation go away, I decided to replace the 100 with a constant:
public static final double HUNDRED = 100; // change it and I'll kill you
In my real project there are many lines using 100, and if I put // NOSONAR
on all those lines that might cover up other potential problems that other developers might inadvertently add later.
Not sure if there will be any real benefits using this constant. A small one may be that when I do git grep 100
I see a lot of matches from resource files in the project, while git grep HUNDRED
turns up just the the Java code that uses this.
100
here would just be obfuscation. However, I feel you aren't looking for a code review of that very small snippet, but for best practices regarding such cases, which unfortunately is an opinion-based question. \$\endgroup\$getPercent
! \$\endgroup\$HUNDRED
is absolutely as useless as100
, and potentially even more harmful since someone could ignore your comment and change it. If anything it proves that it matches the "practical magic number rule" and shouldn't be a variable, final or not. \$\endgroup\$