View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule.design;
5   
6   import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
7   import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
8   import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
9   import net.sourceforge.pmd.lang.rule.properties.IntegerProperty;
10  
11  public class AvoidDeeplyNestedIfStmtsRule extends AbstractJavaRule {
12  
13      private int depth;
14      private int depthLimit;
15      
16      private static final IntegerProperty PROBLEM_DEPTH_DESCRIPTOR = new IntegerProperty(
17      		"problemDepth", 
18      		"The if statement depth reporting threshold",
19      		1, 25,
20      		3,
21      		1.0f
22      		);
23      
24      public AvoidDeeplyNestedIfStmtsRule() {
25  	definePropertyDescriptor(PROBLEM_DEPTH_DESCRIPTOR);
26      }
27    
28      public Object visit(ASTCompilationUnit node, Object data) {
29          depth = 0;
30          depthLimit = getProperty(PROBLEM_DEPTH_DESCRIPTOR);
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  }