View Javadoc

1   /*
2    * SingularField.java
3    *
4    * Created on April 17, 2005, 9:49 PM
5    */
6   
7   package net.sourceforge.pmd.rules;
8   
9   import net.sourceforge.pmd.AbstractRule;
10  import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
11  import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
12  import net.sourceforge.pmd.ast.ASTFieldDeclaration;
13  import net.sourceforge.pmd.ast.ASTMethodDeclaration;
14  import net.sourceforge.pmd.ast.ASTMethodDeclarator;
15  import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
16  import org.jaxen.JaxenException;
17  
18  import java.util.List;
19  
20  /***
21   * @author Eric Olander
22   */
23  public class SingularField extends AbstractRule {
24  
25      public Object visit(ASTFieldDeclaration node, Object data) {
26          if (node.isPrivate() && !node.isStatic()) {
27              List list = node.findChildrenOfType(ASTVariableDeclaratorId.class);
28              ASTVariableDeclaratorId decl = (ASTVariableDeclaratorId) list.get(0);
29              String name = decl.getImage();
30              String path = "//MethodDeclaration[.//PrimaryExpression[.//Name[@Image = \"" + name + "\" or substring-before(@Image, \".\") = \"" + name + "\"] or .//PrimarySuffix[@Image = \"" + name + "\"]]] |" +
31                      "//ConstructorDeclaration[.//PrimaryExpression[.//Name[@Image = \"" + name + "\" or substring-before(@Image, \".\") = \"" + name + "\"] or .//PrimarySuffix[@Image = \"" + name + "\"]]]";
32              try {
33                  List nodes = node.findChildNodesWithXPath(path);
34                  if (nodes.size() == 1) {
35                      String method;
36                      if (nodes.get(0) instanceof ASTMethodDeclaration) {
37                          method = ((ASTMethodDeclarator) ((ASTMethodDeclaration) nodes.get(0)).findChildrenOfType(ASTMethodDeclarator.class).get(0)).getImage();
38                      } else {
39                          ASTConstructorDeclaration astConstructorDeclaration = (ASTConstructorDeclaration) nodes.get(0);
40                          ASTClassOrInterfaceDeclaration astClassOrInterfaceDeclaration = (ASTClassOrInterfaceDeclaration) astConstructorDeclaration.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
41                          if (astClassOrInterfaceDeclaration == null) {
42                              return data;
43                          }
44                          method = astClassOrInterfaceDeclaration.getImage();
45                      }
46                      addViolation(data, decl, new Object[]{name, method});
47                  }
48              } catch (JaxenException je) {
49                  je.printStackTrace();
50              }
51          }
52          return data;
53      }
54  
55  }