1 /***
2 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3 */
4 package net.sourceforge.pmd.rules.design;
5
6 import net.sourceforge.pmd.AbstractRule;
7 import net.sourceforge.pmd.RuleContext;
8 import net.sourceforge.pmd.ast.ASTAssignmentOperator;
9 import net.sourceforge.pmd.ast.ASTNullLiteral;
10 import net.sourceforge.pmd.ast.ASTStatementExpression;
11 import net.sourceforge.pmd.ast.SimpleNode;
12
13 /***
14 * @author dpeugh
15 *
16 * This checks for excessive Null Assignments.
17 *
18 * For instance:
19 *
20 * public void foo() {
21 * Object x = null; // OK
22 * // Some stuff
23 * x = new Object(); // Also OK
24 * // Some more stuff
25 * x = null; // BAD
26 * }
27 */
28
29 public class NullAssignmentRule extends AbstractRule {
30
31 public Object visit(ASTStatementExpression expr, Object data) {
32 if (expr.jjtGetNumChildren() <= 2) {
33 return expr.childrenAccept(this, data);
34 }
35
36 if (expr.jjtGetChild(1) instanceof ASTAssignmentOperator) {
37 SimpleNode curr = (SimpleNode) expr.jjtGetChild(2);
38 for (int i = 0; i < 7; i++) {
39 if (curr.jjtGetNumChildren() != 0) {
40 curr = (SimpleNode) curr.jjtGetChild(0);
41 }
42 }
43
44 if (curr instanceof ASTNullLiteral) {
45 RuleContext ctx = (RuleContext) data;
46 ctx.getReport().addRuleViolation(createRuleViolation(ctx, expr.getBeginLine()));
47 }
48
49 return data;
50 } else {
51 return expr.childrenAccept(this, data);
52 }
53 }
54 }
This page was automatically generated by Maven