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 net.sourceforge.pmd.AbstractRule;
7 import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
8 import net.sourceforge.pmd.ast.ASTFieldDeclaration;
9 import net.sourceforge.pmd.ast.ASTMethodDeclaration;
10
11 import java.util.Iterator;
12 import java.util.List;
13
14 public class AvoidFieldNameMatchingMethodName extends AbstractRule {
15
16 public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
17 if (node.isInterface()) {
18 return data;
19 }
20 return super.visit(node, data);
21 }
22
23 public Object visit(ASTFieldDeclaration node, Object data) {
24 String varName = node.getVariableName();
25 String fieldDeclaringType = getDeclaringType(node);
26 if (varName != null) {
27 varName = varName.toLowerCase();
28 ASTClassOrInterfaceDeclaration cl = (ASTClassOrInterfaceDeclaration) node.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
29 if (cl != null) {
30 List methods = cl.findChildrenOfType(ASTMethodDeclaration.class);
31 if (!methods.isEmpty()) {
32 for (Iterator it = methods.iterator(); it.hasNext();) {
33 ASTMethodDeclaration m = (ASTMethodDeclaration) it.next();
34
35 if (fieldDeclaringType.equals(getDeclaringType(m))) {
36 String n = m.getMethodName();
37 if (varName.equals(n.toLowerCase())) {
38 addViolation(data, node);
39 }
40 }
41 }
42 }
43 }
44 }
45 return data;
46 }
47 }