The meaning of integer 0 as an index or counter or bitfield is utterly transparent, and comparisons with 0 are ubiquitous.
Integer 0 should in these cases not be regarded as a magic number.
You should at least provide a switch to allow integer comparisons with 0.
Besides the use of 0 as the beginning index of a sequence, as in
if( i >= 0 )
or as a counter,
if( nItems > 0 )
several other important paradigms are common.
Comparisons with bitfields:
if( ( flags & Flag.IMPORTANT ) != 0 )
This is far more readable than
if( ( flags & Flag.IMPORTANT ) != Flag.EMPTY_BIT_FIELD )
Return value -1 of String.indexOf(), Reader.read() is admittedly a magic number --
Something like String.INDEX_NOT_FOUND would have been better, if the libraries defined it, but it seems to me excessive to bother programmers with defining a constant for each occurrance of
int dot = aString.indexOf( '.' );
if( dot != -1 )
However, one often sees a sensible alternative
if( dot >= 0 )
This alternative is transparent, and should be permissible. If you listed this in your documentation showing alternatives, there would be much less objection to this rule.
On the other hand, many misfortunes result from floating-point comparisons with 0.0:
if( diff != 0.0 )
if( diff > 0.0 )
It is arguable that the realities of floating-point arithmetic are better kept in view by
if( diff >= Double.MIN_VALUE )
If you included that in your documentation as an alternative to the questionable comparisons, I thiink the objections would be much reduced.
In my current project, I would leave this rule on, if such a switch to allow integer comparisons with 0 were provided. For now, I have to turn the rule off, as it clutters the report terribly.
Thanks for the suggestions.
I've added a rule property "ignoreMagicNumbers" with which you can control the literals, that should be allowed. By default "-1" and "0" are allowed.
This will be included in the next release.