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.ASTClassOrInterfaceType;
    9   import net.sourceforge.pmd.ast.ASTCompilationUnit;
    10  import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
    11  import net.sourceforge.pmd.ast.ASTFieldDeclaration;
    12  import net.sourceforge.pmd.ast.ASTMethodDeclaration;
    13  import net.sourceforge.pmd.ast.ASTResultType;
    14
    15  public class UseSingleton extends AbstractRule {
    16
    17      private boolean isOK;
    18      private int methodCount;
    19
    20      public Object visit(ASTCompilationUnit cu, Object data) {
    21          methodCount = 0;
    22          isOK = false;
    23          Object result = cu.childrenAccept(this, data);
    24          if (!isOK && methodCount > 0) {
    25              addViolation(data, cu);
    26          }
    27
    28          return result;
    29      }
    30
    31      public Object visit(ASTFieldDeclaration decl, Object data) {
    32          if (!decl.isStatic()) {
    33              isOK = true;
    34          }
    35          return data;
    36      }
    37
    38      public Object visit(ASTConstructorDeclaration decl, Object data) {
    39          if (decl.isPrivate()) {
    40              isOK = true;
    41          }
    42          return data;
    43      }
    44
    45      public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) {
    46          if (decl.isAbstract()) {
    47              isOK = true;
    48          }
    49          return super.visit(decl, data);
    50      }
    51
    52      public Object visit(ASTMethodDeclaration decl, Object data) {
    53          methodCount++;
    54
    55          if (!isOK && !decl.isStatic()) {
    56              isOK = true;
    57          }
    58
    59          // TODO use symbol table
    60          if (decl.getMethodName().equals("suite")) {
    61              ASTResultType res = (ASTResultType) decl.getFirstChildOfType(ASTResultType.class);
    62              ASTClassOrInterfaceType c = (ASTClassOrInterfaceType) res.getFirstChildOfType(ASTClassOrInterfaceType.class);
    63              if (c != null && c.getImage().equals("Test")) {
    64                  isOK = true;
    65              }
    66          }
    67
    68          return data;
    69      }
    70
    71  }