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.RuleContext; 8 import net.sourceforge.pmd.ast.ASTClassDeclaration; 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.ASTUnmodifiedClassDeclaration; 14 15 public class UseSingletonRule 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 RuleContext ctx = (RuleContext) data; 26 ctx.getReport().addRuleViolation(createRuleViolation(ctx, cu.getBeginLine())); 27 } 28 29 return result; 30 } 31 32 public Object visit(ASTFieldDeclaration decl, Object data) { 33 isOK = true; 34 return data; 35 } 36 37 public Object visit(ASTConstructorDeclaration decl, Object data) { 38 if (decl.isPrivate()) { 39 isOK = true; 40 } 41 return data; 42 } 43 44 public Object visit(ASTUnmodifiedClassDeclaration decl, Object data) { 45 if (decl.jjtGetParent() instanceof ASTClassDeclaration && ((ASTClassDeclaration)decl.jjtGetParent()).isAbstract()) { 46 isOK = true; 47 } 48 return super.visit(decl, data); 49 } 50 51 public Object visit(ASTMethodDeclaration decl, Object data) { 52 methodCount++; 53 54 if (!isOK && !decl.isStatic()) { 55 isOK = true; 56 } 57 58 return data; 59 } 60 61 }