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