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 net.sourceforge.pmd.ast.ASTAllocationExpression;
    7   import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
    8   import net.sourceforge.pmd.ast.ASTDoStatement;
    9   import net.sourceforge.pmd.ast.ASTForStatement;
    10  import net.sourceforge.pmd.ast.ASTReturnStatement;
    11  import net.sourceforge.pmd.ast.ASTThrowStatement;
    12  import net.sourceforge.pmd.ast.ASTWhileStatement;
    13
    14  public class AvoidInstantiatingObjectsInLoops extends AbstractOptimizationRule {
    15
    16      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    17          if (node.isInterface()) {
    18              return data;
    19          }
    20          return super.visit(node, data);
    21      }
    22
    23
    24      public Object visit(ASTAllocationExpression node, Object data) {
    25          if (insideLoop(node) && fourthParentNotThrow(node) && fourthParentNotReturn(node)) {
    26              addViolation(data, node);
    27          }
    28          return data;
    29      }
    30
    31      private boolean fourthParentNotThrow(ASTAllocationExpression node) {
    32          return !(node.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTThrowStatement);
    33      }
    34
    35      private boolean fourthParentNotReturn(ASTAllocationExpression node) {
    36          return !(node.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTReturnStatement);
    37      }
    38
    39      private boolean insideLoop(ASTAllocationExpression node) {
    40          if (node.getFirstParentOfType(ASTDoStatement.class) != null) {
    41              return true;
    42          }
    43          if (node.getFirstParentOfType(ASTWhileStatement.class) != null) {
    44              return true;
    45          }
    46          if (node.getFirstParentOfType(ASTForStatement.class) != null) {
    47              return true;
    48          }
    49          return false;
    50      }
    51  }