Class VariableDeclarationUsageDistanceCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class VariableDeclarationUsageDistanceCheck
    extends AbstractCheck

    Checks the distance between declaration of variable and its first usage.

    ATTENTION!! (Not supported cases)

     Case #1:
     {
       int c;
       int a = 3;
       int b = 2;
         {
           a = a + b;
           c = b;
         }
     }
     

    Distance for variable 'a' = 1; Distance for variable 'b' = 1; Distance for variable 'c' = 2.

    As distance by default is 1 the Check doesn't raise warning for variables 'a' and 'b' to move them into the block.

    Case #2:

     int sum = 0;
     for (int i = 0; i < 20; i++) {
       a++;
       b--;
       sum++;
       if (sum > 10) {
         res = true;
       }
     }
     

    Distance for variable 'sum' = 3.

    As the distance is more than the default one, the Check raises warning for variable 'sum' to move it into the 'for(...)' block. But there is situation when variable 'sum' hasn't to be 0 within each iteration. So, to avoid such warnings you can use Suppression Filter, provided by Checkstyle, for the whole class.

    • Property allowedDistance - Specify distance between declaration of variable and its first usage. Values should be greater than 0. Type is int. Default value is 3.
    • Property ignoreVariablePattern - Define RegExp to ignore distance calculation for variables listed in this pattern. Type is java.util.regex.Pattern. Default value is "".
    • Property validateBetweenScopes - Allow to calculate the distance between declaration of variable and its first usage in the different scopes. Type is boolean. Default value is false.
    • Property ignoreFinal - Allow to ignore variables with a 'final' modifier. Type is boolean. Default value is true.

    To configure the check:

    Example #1:

     int count;
     a = a + b;
     b = a + a;
     count = b; // DECLARATION OF VARIABLE 'count'
                // SHOULD BE HERE (distance = 3)
     

    Example #2:

     int count;
     {
       a = a + b;
       count = b; // DECLARATION OF VARIABLE 'count'
                  // SHOULD BE HERE (distance = 2)
     }
     

    Check can detect a block of initialization methods. If a variable is used in such a block and there is no other statements after this variable then distance=1.

    Case #1:

     int minutes = 5;
     Calendar cal = Calendar.getInstance();
     cal.setTimeInMillis(timeNow);
     cal.set(Calendar.SECOND, 0);
     cal.set(Calendar.MILLISECOND, 0);
     cal.set(Calendar.HOUR_OF_DAY, hh);
     cal.set(Calendar.MINUTE, minutes);
     

    The distance for the variable minutes is 1 even though this variable is used in the fifth method's call.

    Case #2:

     int minutes = 5;
     Calendar cal = Calendar.getInstance();
     cal.setTimeInMillis(timeNow);
     cal.set(Calendar.SECOND, 0);
     cal.set(Calendar.MILLISECOND, 0);
     System.out.println(cal);
     cal.set(Calendar.HOUR_OF_DAY, hh);
     cal.set(Calendar.MINUTE, minutes);
     

    The distance for the variable minutes is 6 because there is one more expression (except the initialization block) between the declaration of this variable and its usage.

    An example how to configure this Check:

     <module name="VariableDeclarationUsageDistance"/>
     

    An example of how to configure this Check: - to set the allowed distance to 4; - to ignore variables with prefix '^temp'; - to force the validation between scopes; - to check the final variables;

     <module name="VariableDeclarationUsageDistance">
       <property name="allowedDistance" value="4"/>
       <property name="ignoreVariablePattern" value="^temp.*"/>
       <property name="validateBetweenScopes" value="true"/>
       <property name="ignoreFinal" value="false"/>
     </module>
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Violation Message Keys:

    • variable.declaration.usage.distance
    • variable.declaration.usage.distance.extend
    Since:
    5.8
    • Field Detail

      • MSG_KEY

        public static final java.lang.String MSG_KEY
        Warning message key.
        See Also:
        Constant Field Values
      • MSG_KEY_EXT

        public static final java.lang.String MSG_KEY_EXT
        Warning message key.
        See Also:
        Constant Field Values
    • Constructor Detail

      • VariableDeclarationUsageDistanceCheck

        public VariableDeclarationUsageDistanceCheck()
    • Method Detail

      • setAllowedDistance

        public void setAllowedDistance​(int allowedDistance)
        Setter to specify distance between declaration of variable and its first usage. Values should be greater than 0.
        Parameters:
        allowedDistance - Allowed distance between declaration of variable and its first usage.
      • setIgnoreVariablePattern

        public void setIgnoreVariablePattern​(java.util.regex.Pattern pattern)
        Setter to define RegExp to ignore distance calculation for variables listed in this pattern.
        Parameters:
        pattern - a pattern.
      • setValidateBetweenScopes

        public void setValidateBetweenScopes​(boolean validateBetweenScopes)
        Setter to allow to calculate the distance between declaration of variable and its first usage in the different scopes.
        Parameters:
        validateBetweenScopes - Defines if allow to calculate distance between declaration of variable and its first usage in different scopes or not.
      • setIgnoreFinal

        public void setIgnoreFinal​(boolean ignoreFinal)
        Setter to allow to ignore variables with a 'final' modifier.
        Parameters:
        ignoreFinal - Defines if ignore variables with 'final' modifier or not.
      • 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