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.design;
    5
    6   import net.sourceforge.pmd.lang.java.rule.AbstractInefficientZeroCheck;
    7   import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
    8   import net.sourceforge.pmd.util.CollectionUtil;
    9
    10  /**
    11   * Detect structures like "foo.size() == 0" and suggest replacing them with
    12   * foo.isEmpty(). Will also find != 0 (replaceable with !isEmpty()).
    13   *
    14   * @author Jason Bennett
    15   */
    16  public class UseCollectionIsEmptyRule extends AbstractInefficientZeroCheck {
    17
    18      public boolean appliesToClassName(String name){
    19          return CollectionUtil.isCollectionType(name, true);
    20      }
    21
    22      /**
    23       * Determine if we're dealing with .size method
    24       *
    25       * @param occ
    26       *            The name occurrence
    27       * @return true if it's .length, else false
    28       */
    29      public boolean isTargetMethod(NameOccurrence occ) {
    30          if (occ.getNameForWhichThisIsAQualifier() != null) {
    31              if (occ.getLocation().getImage().endsWith(".size")) {
    32                  return true;
    33              }
    34          }
    35          return false;
    36      }
    37  }