1 package net.sourceforge.pmd.rules.strings; 2 3 import net.sourceforge.pmd.ast.Node; 4 import net.sourceforge.pmd.ast.SimpleNode; 5 import net.sourceforge.pmd.rules.AbstractInefficientZeroCheck; 6 import net.sourceforge.pmd.symboltable.NameOccurrence; 7 8 /** 9 * 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 AbstractInefficientZeroCheck { 26 27 /** 28 * Determine if we're dealing with String.length method 29 * 30 * @param occ 31 * The name occurance 32 * @return true if it's String.length, else false 33 */ 34 public boolean isTargetMethod(NameOccurrence occ) { 35 if (occ.getNameForWhichThisIsAQualifier() != null 36 && occ.getNameForWhichThisIsAQualifier().getImage().indexOf("trim") != -1) { 37 Node pExpression = occ.getLocation().jjtGetParent().jjtGetParent(); 38 if (pExpression.jjtGetNumChildren() >= 3 39 && "length".equals(((SimpleNode) pExpression.jjtGetChild(2)).getImage())) { 40 return true; 41 } 42 } 43 return false; 44 } 45 46 public boolean appliesToClassName(String name) { 47 return "String".equals(name); 48 } 49 50 }