01: package com.mycompany.checks;
02:
03: import com.puppycrawl.tools.checkstyle.api.*;
04:
05: public class MethodLimitCheck extends Check {
06: /** the maximum number of methods per class/interface */
07: private int max = 30;
08:
09: /**
10: * Give user a chance to configure max in the config file.
11: * @param aMax the user specified maximum parsed from configuration property.
12: */
13: public void setMax(int aMax) {
14: max = aMax;
15: }
16:
17: /**
18: * We are interested in CLASS_DEF and INTERFACE_DEF Tokens.
19: * @see Check
20: */
21: public int[] getDefaultTokens() {
22: return new int[] { TokenTypes.CLASS_DEF,
23: TokenTypes.INTERFACE_DEF };
24: }
25:
26: /**
27: * @see Check
28: */
29: public void visitToken(DetailAST ast) {
30: // the tree below a CLASS_DEF/INTERFACE_DEF looks like this:
31:
32: // CLASS_DEF
33: // MODIFIERS
34: // class name (IDENT token type)
35: // EXTENDS_CLAUSE
36: // IMPLEMENTS_CLAUSE
37: // OBJBLOCK
38: // {
39: // some other stuff like variable declarations etc.
40: // METHOD_DEF
41: // more stuff, the users might mix methods, variables, etc.
42: // METHOD_DEF
43: // ...and so on
44: // }
45:
46: // We use helper methods to navigate in the syntax tree
47:
48: // find the OBJBLOCK node below the CLASS_DEF/INTERFACE_DEF
49: DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
50:
51: // count the number of direct children of the OBJBLOCK
52: // that are METHOD_DEFS
53: int methodDefs = objBlock.getChildCount(TokenTypes.METHOD_DEF);
54:
55: // report error if limit is reached
56: if (methodDefs > max) {
57: log(ast.getLineNo(), "too.many.methods", new Integer(max));
58: }
59: }
60: }
|