View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.rules.optimization;
    5
    6   import java.util.List;
    7   import java.util.Map;
    8
    9   import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration;
    10  import net.sourceforge.pmd.symboltable.NameOccurrence;
    11  import net.sourceforge.pmd.symboltable.Scope;
    12  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
    13
    14  public class LocalVariableCouldBeFinal extends AbstractOptimizationRule {
    15
    16      public Object visit(ASTLocalVariableDeclaration node, Object data) {
    17          if (node.isFinal()) {
    18              return data;
    19          }
    20          Scope s = node.getScope();
    21          Map<VariableNameDeclaration, List<NameOccurrence>> decls = s.getVariableDeclarations();
    22          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry: decls.entrySet()) {
    23              VariableNameDeclaration var = entry.getKey();
    24              if (var.getAccessNodeParent() != node) {
    25                  continue;
    26              }
    27              if (!assigned(entry.getValue())) {
    28                  addViolation(data, var.getAccessNodeParent(), var.getImage());
    29              }
    30          }
    31          return data;
    32      }
    33
    34  }