Class MagicNumberCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class MagicNumberCheck
    extends AbstractCheck

    Checks that there are no "magic numbers" where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.

    Constant definition is any variable/field that has 'final' modifier. It is fine to have one constant defining multiple numeric literals within one expression:

     static final int SECONDS_PER_DAY = 24 * 60 * 60;
     static final double SPECIAL_RATIO = 4.0 / 3.0;
     static final double SPECIAL_SUM = 1 + Math.E;
     static final double SPECIAL_DIFFERENCE = 4 - Math.PI;
     static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder(3, 3, 3, 3);
     static final Integer ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE = new Integer(42);
     

    Check have following options: ignoreHashCodeMethod - ignore magic numbers in hashCode methods; ignoreAnnotation - ignore magic numbers in annotation declarations; ignoreFieldDeclaration - ignore magic numbers in field declarations.

    To configure the check with default configuration:

     <module name="MagicNumber"/>
     

    results is following violations:

     
       {@literal @}MyAnnotation(6) // violation
       class MyClass {
           private field = 7; // violation
    
           void foo() {
              int i = i + 1; // no violation
              int j = j + 8; // violation
           }
       }
     
     

    To configure the check so that it checks floating-point numbers that are not 0, 0.5, or 1:

       <module name="MagicNumber">
           <property name="tokens" value="NUM_DOUBLE, NUM_FLOAT"/>
           <property name="ignoreNumbers" value="0, 0.5, 1"/>
           <property name="ignoreFieldDeclaration" value="true"/>
           <property name="ignoreAnnotation" value="true"/>
       </module>
     

    results is following violations:

     
       {@literal @}MyAnnotation(6) // no violation
       class MyClass {
           private field = 7; // no violation
    
           void foo() {
              int i = i + 1; // no violation
              int j = j + (int)0.5; // no violation
           }
       }
     
     

    Config example of constantWaiverParentToken option:

       <module name="MagicNumber">
           <property name="constantWaiverParentToken" value="ASSIGN,ARRAY_INIT,EXPR,
           UNARY_PLUS, UNARY_MINUS, TYPECAST, ELIST, DIV, PLUS "/>
       </module>
     

    result is following violation:

     
     class TestMethodCall {
         public void method2() {
             final TestMethodCall dummyObject = new TestMethodCall(62);    //violation
             final int a = 3;        // ok as waiver is ASSIGN
             final int [] b = {4, 5} // ok as waiver is ARRAY_INIT
             final int c = -3;       // ok as waiver is UNARY_MINUS
             final int d = +4;       // ok as waiver is UNARY_PLUS
             final int e = method(1, 2) // ELIST is there but violation due to METHOD_CALL
             final int x = 3 * 4;    // violation
             final int y = 3 / 4;    // ok as waiver is DIV
             final int z = 3 + 4;    // ok as waiver is PLUS
             final int w = 3 - 4;    // violation
             final int x = (int)(3.4);    //ok as waiver is TYPECAST
         }
     }
     
     
    • Field Detail

      • MSG_KEY

        public static final java.lang.String MSG_KEY
        A key is pointing to the warning message text in "messages.properties" file.
        See Also:
        Constant Field Values
      • constantWaiverParentToken

        private int[] constantWaiverParentToken
        The token types that are allowed in the AST path from the number literal to the enclosing constant definition.
      • ignoreNumbers

        private double[] ignoreNumbers
        The numbers to ignore in the check, sorted.
      • ignoreHashCodeMethod

        private boolean ignoreHashCodeMethod
        Whether to ignore magic numbers in a hash code method.
      • ignoreAnnotation

        private boolean ignoreAnnotation
        Whether to ignore magic numbers in annotation.
      • ignoreFieldDeclaration

        private boolean ignoreFieldDeclaration
        Whether to ignore magic numbers in field declaration.
    • Constructor Detail

      • MagicNumberCheck

        public MagicNumberCheck()
        Constructor for MagicNumber Check. Sort the allowedTokensBetweenMagicNumberAndConstDef array for binary search.
    • Method Detail

      • getDefaultTokens

        public int[] getDefaultTokens()
        Description copied from class: AbstractCheck
        Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.
        Specified by:
        getDefaultTokens in class AbstractCheck
        Returns:
        the default tokens
        See Also:
        TokenTypes
      • getAcceptableTokens

        public int[] getAcceptableTokens()
        Description copied from class: AbstractCheck
        The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.
        Specified by:
        getAcceptableTokens in class AbstractCheck
        Returns:
        the token set this check is designed for.
        See Also:
        TokenTypes
      • getRequiredTokens

        public int[] getRequiredTokens()
        Description copied from class: AbstractCheck
        The tokens that this check must be registered for.
        Specified by:
        getRequiredTokens in class AbstractCheck
        Returns:
        the token set this must be registered for.
        See Also:
        TokenTypes
      • isMagicNumberExists

        private boolean isMagicNumberExists​(DetailAST ast,
                                            DetailAST constantDefAST)
        Is magic number some where at ast tree.
        Parameters:
        ast - ast token
        constantDefAST - constant ast
        Returns:
        true if magic number is present
      • findContainingConstantDef

        private static DetailAST findContainingConstantDef​(DetailAST ast)
        Finds the constant definition that contains aAST.
        Parameters:
        ast - the AST
        Returns:
        the constant def or null if ast is not contained in a constant definition.
      • reportMagicNumber

        private void reportMagicNumber​(DetailAST ast)
        Reports aAST as a magic number, includes unary operators as needed.
        Parameters:
        ast - the AST node that contains the number to report
      • isInHashCodeMethod

        private static boolean isInHashCodeMethod​(DetailAST ast)
        Determines whether or not the given AST is in a valid hash code method. A valid hash code method is considered to be a method of the signature public int hashCode().
        Parameters:
        ast - the AST from which to search for an enclosing hash code method definition
        Returns:
        true if ast is in the scope of a valid hash code method.
      • isInIgnoreList

        private boolean isInIgnoreList​(DetailAST ast)
        Decides whether the number of an AST is in the ignore list of this check.
        Parameters:
        ast - the AST to check
        Returns:
        true if the number of ast is in the ignore list of this check.
      • isFieldDeclaration

        private static boolean isFieldDeclaration​(DetailAST ast)
        Determines whether or not the given AST is field declaration.
        Parameters:
        ast - AST from which to search for an enclosing field declaration
        Returns:
        true if ast is in the scope of field declaration
      • setConstantWaiverParentToken

        public void setConstantWaiverParentToken​(java.lang.String... tokens)
        Sets the tokens which are allowed between Magic Number and defined Object.
        Parameters:
        tokens - The string representation of the tokens interested in
      • setIgnoreNumbers

        public void setIgnoreNumbers​(double... list)
        Sets the numbers to ignore in the check. BeanUtils converts numeric token list to double array automatically.
        Parameters:
        list - list of numbers to ignore.
      • setIgnoreHashCodeMethod

        public void setIgnoreHashCodeMethod​(boolean ignoreHashCodeMethod)
        Set whether to ignore hashCode methods.
        Parameters:
        ignoreHashCodeMethod - decide whether to ignore hash code methods
      • setIgnoreAnnotation

        public void setIgnoreAnnotation​(boolean ignoreAnnotation)
        Set whether to ignore Annotations.
        Parameters:
        ignoreAnnotation - decide whether to ignore annotations
      • setIgnoreFieldDeclaration

        public void setIgnoreFieldDeclaration​(boolean ignoreFieldDeclaration)
        Set whether to ignore magic numbers in field declaration.
        Parameters:
        ignoreFieldDeclaration - decide whether to ignore magic numbers in field declaration
      • isChildOf

        private static boolean isChildOf​(DetailAST ast,
                                         int type)
        Determines if the given AST node has a parent node with given token type code.
        Parameters:
        ast - the AST from which to search for annotations
        type - the type code of parent token
        Returns:
        true if the AST node has a parent with given token type.