View Javadoc

    1   package net.sourceforge.pmd.lang.java.rule.strings;
    2
    3   import net.sourceforge.pmd.lang.ast.Node;
    4   import net.sourceforge.pmd.lang.java.rule.AbstractInefficientZeroCheck;
    5   import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
    6
    7   /**
    8    * This rule finds code which inefficiently determines empty strings. This code
    9    * <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  }