View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.rules.design;
    5
    6   import net.sourceforge.pmd.AbstractRule;
    7   import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
    8   import net.sourceforge.pmd.ast.ASTMethodDeclaration;
    9   import net.sourceforge.pmd.ast.ASTReturnStatement;
    10  import net.sourceforge.pmd.ast.SimpleNode;
    11
    12  import java.util.ArrayList;
    13  import java.util.Iterator;
    14  import java.util.List;
    15
    16  public class OnlyOneReturnRule extends AbstractRule {
    17
    18      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    19          if (node.isInterface()) {
    20              return data;
    21          }
    22          return super.visit(node, data);
    23      }
    24
    25      public Object visit(ASTMethodDeclaration node, Object data) {
    26          if (node.isAbstract()) {
    27              return data;
    28          }
    29
    30          List<ASTReturnStatement> returnNodes = new ArrayList<ASTReturnStatement>();
    31          node.findChildrenOfType(ASTReturnStatement.class, returnNodes, false);
    32          if (returnNodes.size() > 1) {
    33              for (Iterator<ASTReturnStatement> i = returnNodes.iterator(); i.hasNext();) {
    34                  SimpleNode problem = i.next();
    35                  // skip the last one, it's OK
    36                  if (!i.hasNext()) {
    37                      continue;
    38                  }
    39                  addViolation(data, problem);
    40              }
    41          }
    42          return data;
    43      }
    44
    45  }