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.controversial;
    5
    6   import java.util.ArrayList;
    7   import java.util.Iterator;
    8   import java.util.List;
    9
    10  import net.sourceforge.pmd.lang.ast.Node;
    11  import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
    12  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
    13  import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
    14  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    15
    16  public class OnlyOneReturnRule extends AbstractJavaRule {
    17
    18      @Override
    19      public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    20          if (node.isInterface()) {
    21              return data;
    22          }
    23          return super.visit(node, data);
    24      }
    25
    26      @Override
    27      public Object visit(ASTMethodDeclaration node, Object data) {
    28          if (node.isAbstract()) {
    29              return data;
    30          }
    31
    32          List<ASTReturnStatement> returnNodes = new ArrayList<ASTReturnStatement>();
    33          node.findDescendantsOfType(ASTReturnStatement.class, returnNodes, false);
    34          if (returnNodes.size() > 1) {
    35              for (Iterator<ASTReturnStatement> i = returnNodes.iterator(); i.hasNext();) {
    36          	Node problem = i.next();
    37                  // skip the last one, it's OK
    38                  if (!i.hasNext()) {
    39                      continue;
    40                  }
    41                  addViolation(data, problem);
    42              }
    43          }
    44          return data;
    45      }
    46
    47  }