ExcessiveNodeCountRule.java
01 /**
02  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03  */
04 package net.sourceforge.pmd.lang.java.rule.design;
05 
06 import net.sourceforge.pmd.lang.java.ast.JavaNode;
07 import net.sourceforge.pmd.lang.java.rule.AbstractStatisticalJavaRule;
08 import net.sourceforge.pmd.stat.DataPoint;
09 
10 /**
11  * This is a common super class for things which
12  * shouldn't have excessive nodes underneath.
13  <p/>
14  * It expects all "visit" calls to return an
15  * Integer.  It will sum all the values it gets,
16  * and use that as its score.
17  <p/>
18  * To use it, override the "visit" for the nodes that
19  * need to be counted.  On those return "new Integer(1)"
20  <p/>
21  * All others will return 0 (or the sum of counted nodes
22  * underneath.)
23  */
24 
25 public class ExcessiveNodeCountRule extends AbstractStatisticalJavaRule {
26     private Class<?> nodeClass;
27 
28     public ExcessiveNodeCountRule(Class<?> nodeClass) {
29   this.nodeClass = nodeClass;
30     }
31 
32     @Override
33     public Object visit(JavaNode node, Object data) {
34   int numNodes = 0;
35 
36   for (int i = 0; i < node.jjtGetNumChildren(); i++) {
37       Integer treeSize = (Integer) ((JavaNodenode.jjtGetChild(i)).jjtAccept(this, data);
38       numNodes += treeSize;
39   }
40 
41   if (nodeClass.isInstance(node)) {
42       DataPoint point = new DataPoint();
43       point.setNode(node);
44       point.setScore(1.0 * numNodes);
45       point.setMessage(getMessage());
46       addDataPoint(point);
47   }
48 
49   return Integer.valueOf(numNodes);
50     }
51 }