01: package net.sourceforge.pmd.rules.strings;
02:
03: import net.sourceforge.pmd.ast.Node;
04: import net.sourceforge.pmd.ast.SimpleNode;
05: import net.sourceforge.pmd.rules.AbstractInefficientZeroCheck;
06: import net.sourceforge.pmd.symboltable.NameOccurrence;
07:
08: /**
09: * This rule finds code which inefficiently determines empty strings. This code
10: * <p/>
11: *
12: * <pre>
13: * if(str.trim().length()==0){....
14: * </pre>
15: *
16: * <p/> is quite inefficient as trim() causes a new String to be created.
17: * Smarter code to check for an empty string would be: <p/>
18: *
19: * <pre>
20: * Character.isWhitespace(str.charAt(i));
21: * </pre>
22: *
23: * @author acaplan
24: */
25: public class InefficientEmptyStringCheck extends
26: AbstractInefficientZeroCheck {
27:
28: /**
29: * Determine if we're dealing with String.length method
30: *
31: * @param occ
32: * The name occurance
33: * @return true if it's String.length, else false
34: */
35: public boolean isTargetMethod(NameOccurrence occ) {
36: if (occ.getNameForWhichThisIsAQualifier() != null
37: && occ.getNameForWhichThisIsAQualifier().getImage()
38: .indexOf("trim") != -1) {
39: Node pExpression = occ.getLocation().jjtGetParent()
40: .jjtGetParent();
41: if (pExpression.jjtGetNumChildren() >= 3
42: && "length".equals(((SimpleNode) pExpression
43: .jjtGetChild(2)).getImage())) {
44: return true;
45: }
46: }
47: return false;
48: }
49:
50: public boolean appliesToClassName(String name) {
51: return "String".equals(name);
52: }
53:
54: }
|