#432 turn off MagicNumber for methods w/particular names

Check (274)
Stephen Bloch

Automated test cases, by their nature, are full of
arbitrary magic numbers. I'd like a way to turn off
MagicNumber checking whenever (for example) I'm inside
a method whose name matches the regular expression
"test.". Or perhaps whenever I'm inside a class whose
name matches "Test.

(I gather that the New, Improved, Java 1.5 version of
JUnit involves annotations, so Feature Request 1229929
might cover this, as long as one is using New,
Improved, Java 1.5 JUnit tests, which I have to confess
I haven't learned to use yet.)


  • Andrew

    Logged In: YES

    Would also be good to disable this test within an array
    that is static final.

  • Lars Kühne
    Lars Kühne

    Logged In: YES

    zzalsar4: MagicNumber does not report violations for static
    final arrays. I think this has been fixed in 3.5 or so (see
    Release Notes, fixed bug "MagicNumber overly aggressive")

    The following code generates no violations in the current
    code base, only if static or final modifier is removed:

    public class Test
    public static final int[] FIRST_PRIMES = {1, 2, 3, 5, 7,
    11, 13, 17};

  • Lars Kühne
    Lars Kühne

    Logged In: YES

    Stephen, would a SuppressionFilter along the lines of

    <suppress checks="MagicNumber" files="Test.*.java"/>

    solve your problem? (Please consult the Configuration docs
    for the full XML file required for SuppressionFilters)

  • Andrew

    Logged In: YES

    You are right - it doesn't! What it does do is disallow
    magic numbers if the definition of the variable includes
    maths e.g.
    private static final double K2 =
    2 * Math.cos(Math.PI / 8); // 1.8477590650225735

    I could just replace the constant K2 with the commented
    number, but I would think that this makes the code worse!
    Checkstyle tells me that 2 and 8 are magic (which they are
    kind of, but better than the commented number). I also
    can't define a variable such as:
    private static final int WIDTH = 10;
    private static final int HALFWIDTH = WIDTH / 2;
    where the definition of 2 is obvious.

    It would be better if the check could be turned off
    entirly for static final variables.

  • Lars Kühne
    Lars Kühne

    Logged In: YES

    zzalsar4: I would simply include 2 and 8 to the list of
    ignored numbers, as I would not want to allow code like
    "HEIGHT = WIDTH / 17 + 53".

    If modifying the ignoredNumbers is not sufficient for you
    and you still want to disable the check for static final
    variables please open a seperate RFE - this one is used to
    track Stephen's original request. It will be closed once
    Stephen's problem is solved.