View Javadoc

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