[java] New rule: VariableDeclarationUsageDistance#6640
Conversation
|
Compared to main: (comment created at 2026-05-09 15:00:43+00:00 for af55b15) |
Co-authored-by: UncleOwen <[email protected]>
adangel
left a comment
There was a problem hiding this comment.
Thanks!
I'd appreciate a sentence for the release notes (something like https://github.com/pmd/pmd/blob/e6e7f330476570623147bfe8805fcf89bde29c7d/docs/pages/release_notes_old.md?plain=1#L24)
| } | ||
| } | ||
| if (!referencedEarly) { | ||
| asCtx(data).addViolation(node, id.getName()); |
There was a problem hiding this comment.
Should we report in the message the max_distance value as well? For the rules that are related to metrics, we had a feature request to always report the actual value and the configured limit.
I think, we can't report the actual distance from declaration to first usage, can we? Would this be too expensive?
E.g. something like "Declaration of ''{0}'' is ''{1}'' statements away from its first usage. It can be moved closer. The max distance allowed is ''{2}''".
| public class Bar { | ||
| public int lengthSumOf(String[] strings) { | ||
| int sum = 0; // premature | ||
| final int offset = 42; // this is final: not a problem |
There was a problem hiding this comment.
Can you explain the reasoning behind why final local vars are excluded? I think, we should put this into the rule description.
Atm I don't see a reason, why offset shouldn't be moved right before the return statement...
There was a problem hiding this comment.
I guess the main reason is that sometimes you want to make a "snapshot" of some object's state before that object is changed and use that snapshot after. Checkstyle rule has a setting for this, by default distances for final variables are ignored there (I didn't find any additional reasoning in sevntu-checkstyle/sevntu.checkstyle#21 where that rule was introduced).
Co-authored-by: Andreas Dangel <[email protected]>
Co-authored-by: Andreas Dangel <[email protected]>
adangel
left a comment
There was a problem hiding this comment.
Thanks!
I'll do the minor cleanups myself.
Describe the PR
Similar to PrematureDeclaration, but instead of checking whether the declaration can be moved after a
return/throw, it checks whether it can be moved by a significant number of statements.Violation of this rule suggests that a method is doing many unrelated things.
Relates to Google style guide paragraph 4.8.2.2 https://checkstyle.sourceforge.io/styleguides/google-java-style-20250426/javaguide.html#s4.8.2.2-variables-limited-scope
Equivalent to Checkstyle's VariableDeclarationUsageDistance
Related issues
Ready?
./mvnw clean verifypasses (checked automatically by github actions)