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