Issue #19156: Fix VariableDeclarationUsageDistanceCheck for inner class
Issue: #19156
Fixed false negative of VariableDeclarationUsageDistanceCheck not reporting violation when
- The check's property
validateBetweenScopesis set totrue; - The variable definition and its first usage exceeds the maximum allowed distance; and
- The first usage is inside an inner class.
Root Cause
The method isInitializationSequence() fails to check for method calls in outer scopes.
This method is used to detect initialization sequences from variable first usage up to variable definition. If detected, it exempts the variable from distance check.
If variable definition is in an outer scope, the method is supposed to check inside outer scope as well. However, the current implementation only checks within the inner scope.
Example
Integer t = 5; // violation, 'Distance .* is 3.
nothing(); (1)
list.add(5); (2)
class BClass extends Parent {
@Override
void mm() {
list.add(t); (3)
}
}
The current implementation only checks (3) and concludes yes, it is an initialization sequence; therefore does not report a violation.
After the fix, (2) and (1) will also be checked and violation is reported since nothing(); is not an initialization.
Fix
When we reach the first sibling, we continue to check previous siblings of the parent node (or grandparent or great-grandparent, based on the type of current scope).
I also added an additional set of tests to ensure correct behavior in various nested blocks.
Hi @romani! PR is ready for review. Would appreciate you time to guide me on improving this PR. CI failure seems unrelated.
Github, generate report for VariableDeclarationUsageDistance/all-examples-in-one
Report for VariableDeclarationUsageDistance/all-examples-in-one: https://checkstyle-diff-reports.s3.us-east-2.amazonaws.com/78dc26faa963e4f8efe92b8f1f1ea3098a5ceabd_2026215820/reports/diff/index.html
https://checkstyle-diff-reports.s3.us-east-2.amazonaws.com/78dc26faa963e4f8efe92b8f1f1ea3098a5ceabd_2026215820/reports/diff/apache-ant/index.html#A2 this is likely false positive, imagine componentHelper is also used in IF, both are in IF , so non of them can change location.
https://checkstyle-diff-reports.s3.us-east-2.amazonaws.com/78dc26faa963e4f8efe92b8f1f1ea3098a5ceabd_2026215820/reports/diff/RxJava/index.html#A1 this is better example of false positive. You will unlikely make this code different to avoid violation. Please add it to input .
Just add to Inputs , not sure why we started to report this, but violation is correct: https://checkstyle-diff-reports.s3.us-east-2.amazonaws.com/78dc26faa963e4f8efe92b8f1f1ea3098a5ceabd_2026215820/reports/diff/pmd/index.html#A1