Class InefficientEmptyStringCheckRule

  • All Implemented Interfaces:
    AstVisitor<Object,​Object>, JavaParserVisitor, JavaVisitor<Object,​Object>, PropertySource, Rule

    public class InefficientEmptyStringCheckRule
    extends AbstractJavaRulechainRule
    This rule finds code which inefficiently determines empty strings.

     str.trim().length()==0
     
    or
     str.trim().isEmpty()
     
    (for the same reason) is quite inefficient as trim() causes a new String to be created. A Smarter code to check for an empty string would be:
     private boolean checkTrimEmpty(String str) {
         for(int i = 0; i < str.length(); i++) {
             if(!Character.isWhitespace(str.charAt(i))) {
                 return false;
             }
         }
         return true;
     }
     
    or you can refer to Apache's StringUtils#isBlank (in commons-lang), Spring's StringUtils#hasText (in the Spring framework) or Google's CharMatcher#whitespace (in Guava) for existing implementations (some might include the check for != null).

    Author:
    acaplan
    • Constructor Detail

      • InefficientEmptyStringCheckRule

        public InefficientEmptyStringCheckRule()