KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > SingularField


1 /*
2  * SingularField.java
3  *
4  * Created on April 17, 2005, 9:49 PM
5  */

6 package net.sourceforge.pmd.rules;
7
8 import net.sourceforge.pmd.AbstractRule;
9 import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
10 import net.sourceforge.pmd.ast.ASTFieldDeclaration;
11 import net.sourceforge.pmd.ast.ASTInitializer;
12 import net.sourceforge.pmd.ast.ASTMethodDeclaration;
13 import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
14 import net.sourceforge.pmd.ast.SimpleNode;
15 import net.sourceforge.pmd.symboltable.NameOccurrence;
16
17 import java.util.List JavaDoc;
18
19 /**
20  * @author Eric Olander
21  */

22 public class SingularField extends AbstractRule {
23
24     public Object JavaDoc visit(ASTFieldDeclaration node, Object JavaDoc data) {
25         if (node.isPrivate() && !node.isStatic()) {
26             List JavaDoc list = node.findChildrenOfType(ASTVariableDeclaratorId.class);
27             ASTVariableDeclaratorId declaration = (ASTVariableDeclaratorId) list.get(0);
28             List JavaDoc usages = declaration.getUsages();
29             SimpleNode decl = null;
30             boolean violation = true;
31             for (int ix = 0; ix < usages.size(); ix++) {
32                 NameOccurrence no = (NameOccurrence) usages.get(ix);
33                 SimpleNode location = no.getLocation();
34
35                 SimpleNode method = (SimpleNode) location.getFirstParentOfType(ASTMethodDeclaration.class);
36                 if (method == null) {
37                     method = (SimpleNode) location.getFirstParentOfType(ASTConstructorDeclaration.class);
38                     if (method == null) {
39                         method = (SimpleNode) location.getFirstParentOfType(ASTInitializer.class);
40                         if (method == null) {
41                             continue;
42                         }
43                     }
44                 }
45
46                 if (decl == null) {
47                     decl = method;
48                     continue;
49                 } else if (decl != method) {
50
51                     violation = false;
52                 }
53             }
54
55             if (violation && !usages.isEmpty()) {
56                 addViolation(data, node, new Object JavaDoc[] { declaration.getImage() });
57             }
58         }
59         return data;
60     }
61 }
62
Popular Tags