View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.naming;
21  
22  import com.puppycrawl.tools.checkstyle.api.DetailAST;
23  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
24  import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
25  
26  /**
27   * <p>
28   * Checks that method names conform to a specified pattern.
29   * </p>
30   *
31   * <p>Also, checks if a method name has the same name as the residing class.
32   * The default is false (it is not allowed). It is legal in Java to have
33   * method with the same name as a class. As long as a return type is specified
34   * it is a method and not a constructor which it could be easily confused as.
35   * Does not check-style the name of an overridden methods because the developer does not
36   * have a choice in renaming such methods.
37   * </p>
38   *
39   * <ul>
40   * <li>
41   * Property {@code allowClassName} - Control whether to allow a method name to have the same name
42   * as the enclosing class name. Setting this property {@code false} helps to avoid
43   * confusion between constructors and methods.
44   * Type is {@code boolean}.
45   * Default value is {@code false}.
46   * </li>
47   * <li>
48   * Property {@code applyToPackage} - Control if check should apply to package-private members.
49   * Type is {@code boolean}.
50   * Default value is {@code true}.
51   * </li>
52   * <li>
53   * Property {@code applyToPrivate} - Control if check should apply to private members.
54   * Type is {@code boolean}.
55   * Default value is {@code true}.
56   * </li>
57   * <li>
58   * Property {@code applyToProtected} - Control if check should apply to protected members.
59   * Type is {@code boolean}.
60   * Default value is {@code true}.
61   * </li>
62   * <li>
63   * Property {@code applyToPublic} - Control if check should apply to public members.
64   * Type is {@code boolean}.
65   * Default value is {@code true}.
66   * </li>
67   * <li>
68   * Property {@code format} - Sets the pattern to match valid identifiers.
69   * Type is {@code java.util.regex.Pattern}.
70   * Default value is {@code "^[a-z][a-zA-Z0-9]*$"}.
71   * </li>
72   * </ul>
73   * <p>
74   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
75   * </p>
76   * <p>
77   * Violation Message Keys:
78   * </p>
79   * <ul>
80   * <li>
81   * {@code method.name.equals.class.name}
82   * </li>
83   * <li>
84   * {@code name.invalidPattern}
85   * </li>
86   * </ul>
87   *
88   * @since 3.0
89   */
90  public class MethodNameCheck
91      extends AbstractAccessControlNameCheck {
92  
93      /**
94       * A key is pointing to the warning message text in "messages.properties"
95       * file.
96       */
97      public static final String MSG_KEY = "method.name.equals.class.name";
98  
99      /**
100      * Control whether to allow a method name to have the same name as the enclosing class name.
101      * Setting this property {@code false} helps to avoid confusion
102      * between constructors and methods.
103      */
104     private boolean allowClassName;
105 
106     /** Creates a new {@code MethodNameCheck} instance. */
107     public MethodNameCheck() {
108         super("^[a-z][a-zA-Z0-9]*$");
109     }
110 
111     @Override
112     public int[] getDefaultTokens() {
113         return getRequiredTokens();
114     }
115 
116     @Override
117     public int[] getAcceptableTokens() {
118         return getRequiredTokens();
119     }
120 
121     @Override
122     public int[] getRequiredTokens() {
123         return new int[] {TokenTypes.METHOD_DEF, };
124     }
125 
126     @Override
127     public void visitToken(DetailAST ast) {
128         if (!AnnotationUtil.hasOverrideAnnotation(ast)) {
129             // Will check the name against the format.
130             super.visitToken(ast);
131         }
132 
133         if (!allowClassName) {
134             final DetailAST method =
135                 ast.findFirstToken(TokenTypes.IDENT);
136             // in all cases this will be the classDef type except anon inner
137             // with anon inner classes this will be the Literal_New keyword
138             final DetailAST classDefOrNew = ast.getParent().getParent();
139             final DetailAST classIdent =
140                 classDefOrNew.findFirstToken(TokenTypes.IDENT);
141             // Following logic is to handle when a classIdent can not be
142             // found. This is when you have a Literal_New keyword followed
143             // a DOT, which is when you have:
144             // new Outclass.InnerInterface(x) { ... }
145             // Such a rare case, will not have the logic to handle parsing
146             // down the tree looking for the first ident.
147             if (classIdent != null
148                 && method.getText().equals(classIdent.getText())) {
149                 log(method, MSG_KEY, method.getText());
150             }
151         }
152     }
153 
154     /**
155      * Setter to control whether to allow a method name to have the same name
156      * as the enclosing class name. Setting this property {@code false}
157      * helps to avoid confusion between constructors and methods.
158      *
159      * @param allowClassName true to allow false to disallow
160      * @since 5.0
161      */
162     public void setAllowClassName(boolean allowClassName) {
163         this.allowClassName = allowClassName;
164     }
165 
166 }