View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.rules;
5   
6   import java.util.Map;
7   
8   import net.sourceforge.pmd.AbstractRule;
9   import net.sourceforge.pmd.PropertyDescriptor;
10  import net.sourceforge.pmd.ast.ASTCompilationUnit;
11  import net.sourceforge.pmd.ast.ASTIfStatement;
12  import net.sourceforge.pmd.properties.IntegerProperty;
13  
14  public class AvoidDeeplyNestedIfStmtsRule extends AbstractRule {
15  
16      private int depth;
17      private int depthLimit;
18      
19      private static final PropertyDescriptor problemDepthDescriptor = new IntegerProperty(
20      		"problemDepth", 
21      		"Maximum allowable statement depth",
22      		0,
23      		1.0f
24      		);
25      
26      private static final Map<String, PropertyDescriptor> propertyDescriptorsByName = asFixedMap(problemDepthDescriptor);
27          
28      public Object visit(ASTCompilationUnit node, Object data) {
29          depth = 0;
30          depthLimit = getIntProperty(problemDepthDescriptor);
31          return super.visit(node, data);
32      }
33  
34      public Object visit(ASTIfStatement node, Object data) {
35          if (!node.hasElse()) {
36              depth++;
37          }
38          super.visit(node, data);
39          if (depth == depthLimit) {
40              addViolation(data, node);
41          }
42          depth--;
43          return data;
44      }
45  
46      /**
47       * @return Map
48       */
49      protected Map<String, PropertyDescriptor> propertiesByName() {
50      	return propertyDescriptorsByName;
51      }
52  }