Class VariableDeclarationUsageDistanceCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.coding.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 isint
. Default value is3
. -
Property
ignoreVariablePattern
- Define RegExp to ignore distance calculation for variables listed in this pattern. Type isjava.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 isboolean
. Default value isfalse
. -
Property
ignoreFinal
- Allow to ignore variables with a 'final' modifier. Type isboolean
. Default value istrue
.
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
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.String
MSG_KEY
Warning message key.static java.lang.String
MSG_KEY_EXT
Warning message key.
-
Constructor Summary
Constructors Constructor Description VariableDeclarationUsageDistanceCheck()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.int[]
getRequiredTokens()
The tokens that this check must be registered for.void
setAllowedDistance(int allowedDistance)
Setter to specify distance between declaration of variable and its first usage.void
setIgnoreFinal(boolean ignoreFinal)
Setter to allow to ignore variables with a 'final' modifier.void
setIgnoreVariablePattern(java.util.regex.Pattern pattern)
Setter to define RegExp to ignore distance calculation for variables listed in this pattern.void
setValidateBetweenScopes(boolean validateBetweenScopes)
Setter to allow to calculate the distance between declaration of variable and its first usage in the different scopes.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
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
-
-
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 classAbstractCheck
- 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 classAbstractCheck
- 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 classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
-