Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-1941

Variables should not be declared before they are relevant

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Move the declaration of "xxx" closer to the code that uses it.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Targeted languages:
      C#, C++, Flex, JavaScript, Objective-C, PHP, Python, VB.Net, VB6
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources
    • Checkstyle:
      VariableDeclarationUsageDistance
    • PMD:
      PrematureDeclaration

      Description

      For the sake of clarity, variables should be declared as close to where they're used as possible. This is particularly true when considering methods that contain early returns and the potential to throw exceptions. In these cases, it is not only pointless, but also confusing to declare a variable that may never be used because conditions for an early return are met first.

      Noncompliant Code Example

      public boolean isConditionMet(int a, int b) {
        int difference = a - b;
        MyClass foo = new MyClass(a);  // Noncompliant; not used before early return
        
        if (difference < 0) {
          return false;
        }
      
        // ...
      
        if (foo.doTheThing()) {
          return true;
        }
        return false;
      }
      

      Compliant Solution

      public boolean isConditionMet(int a, int b) {
        int difference = a - b;
        
        if (difference < 0) {
          return false;
        }
      
        // ...
      
        MyClass foo = new MyClass(a);
        if (foo.doTheThing()) {
          return true;
        }
        return false;
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: