public class VariableDeclarationUsageDistanceCheck extends AbstractCheck
Checks the distance between declaration of variable and its first usage. Note : Variable declaration/initialization statements are not counted while calculating length.
allowedDistance - Specify distance between declaration
of variable and its first usage. Values should be greater than 0.
Type is int.
Default value is 3.
ignoreVariablePattern - Define RegExp to ignore distance calculation
for variables listed in this pattern.
Type is java.util.regex.Pattern.
Default value is "".
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.
ignoreFinal - Allow to ignore variables with a 'final' modifier.
Type is boolean.
Default value is true.
To configure the check with default config:
<module name="VariableDeclarationUsageDistance"/>
Example:
public class Test {
public void foo1() {
int num; // violation, distance = 4
final int PI; // OK, final variables not checked
System.out.println("Statement 1");
System.out.println("Statement 2");
System.out.println("Statement 3");
num = 1;
PI = 3.14;
}
public void foo2() {
int a; // OK, used in different scope
int b; // OK, used in different scope
int count = 0; // OK, used in different scope
{
System.out.println("Inside inner scope");
a = 1;
b = 2;
count++;
}
}
}
Check can detect a block of initialization methods. If a variable is used in such a block and there are no other statements after variable declaration, 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.
To configure the check to set allowed distance:
<module name="VariableDeclarationUsageDistance"> <property name="allowedDistance" value="4"/> </module>
Example:
public class Test {
public void foo1() {
int num; // OK, distance = 4
final int PI; // OK, final variables not checked
System.out.println("Statement 1");
System.out.println("Statement 2");
System.out.println("Statement 3");
num = 1;
PI = 3.14;
}
public void foo2() {
int a; // OK, used in different scope
int b; // OK, used in different scope
int count = 0; // OK, used in different scope
{
System.out.println("Inside inner scope");
a = 1;
b = 2;
count++;
}
}
}
To configure the check to ignore certain variables:
<module name="VariableDeclarationUsageDistance"> <property name="ignoreVariablePattern" value="^num$"/> </module>
This configuration ignores variables named "num".
Example:
public class Test {
public void foo1() {
int num; // OK, variable ignored
final int PI; // OK, final variables not checked
System.out.println("Statement 1");
System.out.println("Statement 2");
System.out.println("Statement 3");
num = 1;
PI = 3.14;
}
public void foo2() {
int a; // OK, used in different scope
int b; // OK, used in different scope
int count = 0; // OK, used in different scope
{
System.out.println("Inside inner scope");
a = 1;
b = 2;
count++;
}
}
}
To configure the check to force validation between scopes:
<module name="VariableDeclarationUsageDistance"> <property name="validateBetweenScopes" value="true"/> </module>
Example:
public class Test {
public void foo1() {
int num; // violation, distance = 4
final int PI; // OK, final variables not checked
System.out.println("Statement 1");
System.out.println("Statement 2");
System.out.println("Statement 3");
num = 1;
PI = 3.14;
}
public void foo2() {
int a; // OK, distance = 2
int b; // OK, distance = 3
int count = 0; // violation, distance = 4
{
System.out.println("Inside inner scope");
a = 1;
b = 2;
count++;
}
}
}
To configure the check to check final variables:
<module name="VariableDeclarationUsageDistance"> <property name="ignoreFinal" value="false"/> </module>
Example:
public class Test {
public void foo1() {
int num; // violation, distance = 4
final int PI; // violation, distance = 5
System.out.println("Statement 1");
System.out.println("Statement 2");
System.out.println("Statement 3");
num = 1;
PI = 3.14;
}
public void foo2() {
int a; // OK, used in different scope
int b; // OK, used in different scope
int count = 0; // OK, used in different scope
{
System.out.println("Inside inner scope");
a = 1;
b = 2;
count++;
}
}
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
variable.declaration.usage.distance
variable.declaration.usage.distance.extend
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private int |
allowedDistance
Specify distance between declaration of variable and its first usage.
|
private static int |
DEFAULT_DISTANCE
Default value of distance between declaration of variable and its first
usage.
|
private boolean |
ignoreFinal
Allow to ignore variables with a 'final' modifier.
|
private java.util.regex.Pattern |
ignoreVariablePattern
Define RegExp to ignore distance calculation for variables listed in
this pattern.
|
static java.lang.String |
MSG_KEY
Warning message key.
|
static java.lang.String |
MSG_KEY_EXT
Warning message key.
|
private boolean |
validateBetweenScopes
Allow to calculate the distance between declaration of variable and its
first usage in the different scopes.
|
| Constructor and Description |
|---|
VariableDeclarationUsageDistanceCheck() |
| Modifier and Type | Method and Description |
|---|---|
private static java.util.Map.Entry<DetailAST,java.lang.Integer> |
calculateDistanceBetweenScopes(DetailAST ast,
DetailAST variable)
Calculates distance between declaration of variable and its first usage
in multiple scopes.
|
private static java.util.Map.Entry<DetailAST,java.lang.Integer> |
calculateDistanceInSingleScope(DetailAST semicolonAst,
DetailAST variableIdentAst)
Calculates distance between declaration of variable and its first usage
in single scope.
|
int[] |
getAcceptableTokens()
The configurable token set.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
private static int |
getDistToVariableUsageInChildNode(DetailAST childNode,
DetailAST varIdent,
int currentDistToVarUsage)
Returns the distance to variable usage for in the child node.
|
private static DetailAST |
getFirstCaseGroupOrSwitchRule(DetailAST block)
Helper method for getFirstNodeInsideSwitchBlock to return the first CASE_GROUP or
SWITCH_RULE ast.
|
private static DetailAST |
getFirstNodeInsideForWhileDoWhileBlocks(DetailAST block,
DetailAST variable)
Gets first Ast node inside FOR, WHILE or DO-WHILE blocks if variable
usage is met only inside the block (not in its declaration!).
|
private static DetailAST |
getFirstNodeInsideIfBlock(DetailAST block,
DetailAST variable)
Gets first Ast node inside IF block if variable usage is met
only inside the block (not in its declaration!).
|
private static DetailAST |
getFirstNodeInsideSwitchBlock(DetailAST block,
DetailAST variable)
Gets first Ast node inside SWITCH block if variable usage is met
only inside the block (not in its declaration!).
|
private static DetailAST |
getFirstNodeInsideTryCatchFinallyBlocks(DetailAST block,
DetailAST variable)
Gets first Ast node inside TRY-CATCH-FINALLY blocks if variable usage is
met only inside the block (not in its declaration!).
|
private static java.lang.String |
getInstanceName(DetailAST methodCallAst)
Get name of instance whose method is called.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private static boolean |
isChild(DetailAST parent,
DetailAST ast)
Checks if Ast node contains given element.
|
private static boolean |
isInitializationSequence(DetailAST variableUsageAst,
java.lang.String variableName)
Processes statements until usage of variable to detect sequence of
initialization methods.
|
private static boolean |
isVariableInOperatorExpr(DetailAST operator,
DetailAST variable)
Checks if variable is in operator declaration.
|
private boolean |
isVariableMatchesIgnorePattern(java.lang.String variable)
Checks if entrance variable is contained in ignored pattern.
|
private static java.util.Map.Entry<java.util.List<DetailAST>,java.lang.Integer> |
searchVariableUsageExpressions(DetailAST variableAst,
DetailAST statementAst)
Searches variable usages starting from specified statement.
|
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.
|
beginTree, clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_KEY
public static final java.lang.String MSG_KEY_EXT
private static final int DEFAULT_DISTANCE
private int allowedDistance
private java.util.regex.Pattern ignoreVariablePattern
private boolean validateBetweenScopes
private boolean ignoreFinal
public VariableDeclarationUsageDistanceCheck()
public void setAllowedDistance(int allowedDistance)
allowedDistance - Allowed distance between declaration of variable and its first
usage.public void setIgnoreVariablePattern(java.util.regex.Pattern pattern)
pattern - a pattern.public void setValidateBetweenScopes(boolean validateBetweenScopes)
validateBetweenScopes - Defines if allow to calculate distance between declaration of
variable and its first usage in different scopes or not.public void setIgnoreFinal(boolean ignoreFinal)
ignoreFinal - Defines if ignore variables with 'final' modifier or not.public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processprivate static java.lang.String getInstanceName(DetailAST methodCallAst)
methodCallAst - DetailAST of METHOD_CALL.private static boolean isInitializationSequence(DetailAST variableUsageAst, java.lang.String variableName)
variableUsageAst - DetailAST of expression that uses variable named variableName.variableName - name of considered variable.private static java.util.Map.Entry<DetailAST,java.lang.Integer> calculateDistanceInSingleScope(DetailAST semicolonAst, DetailAST variableIdentAst)
semicolonAst - Regular node of Ast which is checked for content of checking
variable.variableIdentAst - Variable which distance is calculated for.private static int getDistToVariableUsageInChildNode(DetailAST childNode, DetailAST varIdent, int currentDistToVarUsage)
childNode - child node.varIdent - variable variable identifier.currentDistToVarUsage - current distance to the variable usage.private static java.util.Map.Entry<DetailAST,java.lang.Integer> calculateDistanceBetweenScopes(DetailAST ast, DetailAST variable)
ast - Regular node of Ast which is checked for content of checking
variable.variable - Variable which distance is calculated for.private static java.util.Map.Entry<java.util.List<DetailAST>,java.lang.Integer> searchVariableUsageExpressions(DetailAST variableAst, DetailAST statementAst)
variableAst - Variable that is used.statementAst - DetailAST to start searching from.private static DetailAST getFirstNodeInsideForWhileDoWhileBlocks(DetailAST block, DetailAST variable)
block - Ast node represents FOR, WHILE or DO-WHILE block.variable - Variable which is checked for content in block.private static DetailAST getFirstNodeInsideIfBlock(DetailAST block, DetailAST variable)
block - Ast node represents IF block.variable - Variable which is checked for content in block.private static DetailAST getFirstNodeInsideSwitchBlock(DetailAST block, DetailAST variable)
block - Ast node represents SWITCH block.variable - Variable which is checked for content in block.private static DetailAST getFirstCaseGroupOrSwitchRule(DetailAST block)
block - the switch block to check.private static DetailAST getFirstNodeInsideTryCatchFinallyBlocks(DetailAST block, DetailAST variable)
block - Ast node represents TRY-CATCH-FINALLY block.variable - Variable which is checked for content in block.private static boolean isVariableInOperatorExpr(DetailAST operator, DetailAST variable)
boolean b = true;
if (b) {...}
Variable 'b' is in declaration of operator IF.operator - Ast node which represents operator.variable - Variable which is checked for content in operator.private static boolean isChild(DetailAST parent, DetailAST ast)
parent - Node of AST.ast - Ast element which is checked for content in Ast node.private boolean isVariableMatchesIgnorePattern(java.lang.String variable)
variable - Variable which is checked for content in ignored pattern.Copyright © 2001-2022. All Rights Reserved.