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.java.ast.ASTBlockStatement;
7   import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
8   import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
9   
10  /**
11   * This rule finds the following:
12   * <p/>
13   * <pre>
14   *         StringBuffer.append(&quot;c&quot;); // appends a
15   *         single character
16   * </pre>
17   * <p/>
18   * It is preferable to use StringBuffer.append('c'); // appends a single
19   * character Implementation of PMD RFE 1373863
20   */
21  public class AppendCharacterWithCharRule extends AbstractJavaRule {
22  
23      @Override
24      public Object visit(ASTLiteral node, Object data) {
25          ASTBlockStatement bs = node.getFirstParentOfType(ASTBlockStatement.class);
26          if (bs == null) {
27              return data;
28          }
29  
30          if (node.isSingleCharacterStringLiteral()) {
31              if (!InefficientStringBufferingRule.isInStringBufferOperation(node, 8, "append")) {
32                  return data;
33              }
34              addViolation(data, node);
35          }
36          return data;
37      }
38  }