01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
07: import net.sourceforge.pmd.ast.ASTFieldDeclaration;
08: import net.sourceforge.pmd.ast.ASTMethodDeclaration;
09:
10: import java.util.List;
11:
12: public class AvoidFieldNameMatchingMethodName extends AbstractRule {
13:
14: public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
15: if (node.isInterface()) {
16: return data;
17: }
18: return super .visit(node, data);
19: }
20:
21: public Object visit(ASTFieldDeclaration node, Object data) {
22: String varName = node.getVariableName();
23: String fieldDeclaringType = getDeclaringType(node);
24: if (varName != null) {
25: varName = varName.toLowerCase();
26: ASTClassOrInterfaceDeclaration cl = node
27: .getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
28: if (cl != null) {
29: List<ASTMethodDeclaration> methods = cl
30: .findChildrenOfType(ASTMethodDeclaration.class);
31: for (ASTMethodDeclaration m : methods) {
32: //Make sure we are comparing fields and methods inside same type
33: if (fieldDeclaringType.equals(getDeclaringType(m))) {
34: String n = m.getMethodName();
35: if (varName.equals(n.toLowerCase())) {
36: addViolation(data, node);
37: }
38: }
39: }
40: }
41: }
42: return data;
43: }
44: }
|