Skip to content

Files

Latest commit

 

History

History
59 lines (44 loc) · 1.96 KB

VariableDeclarationUsageDistance.md

File metadata and controls

59 lines (44 loc) · 1.96 KB

Pattern: Variable declaration is distanced from it's first usage

Issue: -

Description

This rule enforces recommendation by Google Java Style Guide: Local variables should not be habitually declared at the start of their containing block or block-like construct. Instead, local variables should be declared close to the point they are first used (within reason), to minimize their scope.

Local variable declarations typically have initializers, or are initialized immediately after declaration. Consider making variable final if you still need to store its value in advance (before method calls that might have side effects on the original value).

Default configuration

<module name="VariableDeclarationUsageDistance"/>

Examples

Example of incorrect code:

int minutes = 10;
doSomething();
doSomethingElse();
initialize();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, minutes); // minutes could be declared closer to it's first usage

Example of correct code:

doSomething();
doSomethingElse();
initialize();
Calendar cal = Calendar.getInstance();
int minutes = 10;
cal.set(Calendar.MINUTE, minutes);

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>

Further Reading