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