1 |
| |
2 |
| |
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 |
6
| public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
|
17 |
6
| if (node.isInterface()) {
|
18 |
0
| return data;
|
19 |
| } |
20 |
6
| return super.visit(node, data);
|
21 |
| } |
22 |
| |
23 |
| |
24 |
7
| public Object visit(ASTAllocationExpression node, Object data) {
|
25 |
7
| if (insideLoop(node) && fourthParentNotThrow(node) && fourthParentNotReturn(node)) {
|
26 |
5
| addViolation(data, node);
|
27 |
| } |
28 |
7
| return data;
|
29 |
| } |
30 |
| |
31 |
7
| private boolean fourthParentNotThrow(ASTAllocationExpression node) {
|
32 |
7
| return !(node.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTThrowStatement);
|
33 |
| } |
34 |
| |
35 |
6
| private boolean fourthParentNotReturn(ASTAllocationExpression node) {
|
36 |
6
| return !(node.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTReturnStatement);
|
37 |
| } |
38 |
| |
39 |
7
| private boolean insideLoop(ASTAllocationExpression node) {
|
40 |
7
| if (node.getFirstParentOfType(ASTDoStatement.class) != null) {
|
41 |
3
| return true;
|
42 |
| } |
43 |
4
| if (node.getFirstParentOfType(ASTWhileStatement.class) != null) {
|
44 |
1
| return true;
|
45 |
| } |
46 |
3
| if (node.getFirstParentOfType(ASTForStatement.class) != null) {
|
47 |
3
| return true;
|
48 |
| } |
49 |
0
| return false;
|
50 |
| } |
51 |
| } |