01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules.optimization;
04:
05: import net.sourceforge.pmd.ast.ASTAllocationExpression;
06: import net.sourceforge.pmd.ast.ASTDoStatement;
07: import net.sourceforge.pmd.ast.ASTForStatement;
08: import net.sourceforge.pmd.ast.ASTReturnStatement;
09: import net.sourceforge.pmd.ast.ASTThrowStatement;
10: import net.sourceforge.pmd.ast.ASTWhileStatement;
11:
12: public class AvoidInstantiatingObjectsInLoops extends
13: AbstractOptimizationRule {
14:
15: public Object visit(ASTAllocationExpression node, Object data) {
16: if (insideLoop(node) && fourthParentNotThrow(node)
17: && fourthParentNotReturn(node)) {
18: addViolation(data, node);
19: }
20: return data;
21: }
22:
23: private boolean fourthParentNotThrow(ASTAllocationExpression node) {
24: return !(node.jjtGetParent().jjtGetParent().jjtGetParent()
25: .jjtGetParent() instanceof ASTThrowStatement);
26: }
27:
28: private boolean fourthParentNotReturn(ASTAllocationExpression node) {
29: return !(node.jjtGetParent().jjtGetParent().jjtGetParent()
30: .jjtGetParent() instanceof ASTReturnStatement);
31: }
32:
33: private boolean insideLoop(ASTAllocationExpression node) {
34: if (node.getFirstParentOfType(ASTDoStatement.class) != null) {
35: return true;
36: }
37: if (node.getFirstParentOfType(ASTWhileStatement.class) != null) {
38: return true;
39: }
40: if (node.getFirstParentOfType(ASTForStatement.class) != null) {
41: return true;
42: }
43: return false;
44: }
45: }
|