Skip to content

VariableDeclarationUsageDistanceCheck doesn't handle method definition properly #13038

@jxr98

Description

@jxr98

I have read check documentation: https://checkstyle.org/config_coding.html#VariableDeclarationUsageDistance
I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run
I have executed the cli and showed it below.

https://checkstyle.org/checks/coding/variabledeclarationusagedistance.html#VariableDeclarationUsageDistance

/var/tmp $ javac Test1.java

/var/tmp $ cat config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name = "Checker">
    <module name="TreeWalker">
        <module name="VariableDeclarationUsageDistance">
          <property name="validateBetweenScopes" value="true"/>
          <property name="allowedDistance" value="1"/>
        </module> 
    </module>
</module>

/var/tmp $ cat Test1.java

import java.util.Iterator;

public class Test1 {
    public void method(){
        int a=1;
        class GeneralLogic {
            public <T> Iterator<T> method(T[] b) throws Exception{
                if(a>0){
                    System.out.println(b.length);
                }
                return null;
            }
        }
    }
}


/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US"
/var/tmp $ java $RUN_LOCALE -jar checkstyle-10.9.3-all.jar -c config.xml Test1.java

Starting audit...
[WARN] /var/tmp/Test.java:5:9: Distance between variable 'a' declaration and its first usage is 3,
 but allowed 1.  Consider making that variable final if you still need to store its value in 
advance (before method calls that might have side effects on the original value).
 [VariableDeclarationUsageDistance]
Audit done.

The distance should be 1. This three were caused by generic type which is <T>, parameter type in the method signature and throws. I think the correct distance one should be caused by the expression in the if condition.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions