View Javadoc

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