View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 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   * <div>
28   * Checks that method names conform to a specified pattern.
29   * </div>
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   * @since 3.0
40   */
41  public class MethodNameCheck
42      extends AbstractAccessControlNameCheck {
43  
44      /**
45       * A key is pointing to the warning message text in "messages.properties"
46       * file.
47       */
48      public static final String MSG_KEY = "method.name.equals.class.name";
49  
50      /**
51       * A key is pointing to the warning message text in "messages.properties"
52       * file.
53       */
54      public static final String MSG_INVALID_PATTERN = "name.invalidPattern";
55  
56      /**
57       * Control whether to allow a method name to have the same name as the enclosing class name.
58       * Setting this property {@code false} helps to avoid confusion
59       * between constructors and methods.
60       */
61      private boolean allowClassName;
62  
63      /** Creates a new {@code MethodNameCheck} instance. */
64      public MethodNameCheck() {
65          super("^[a-z][a-zA-Z0-9]*$", MSG_INVALID_PATTERN);
66      }
67  
68      @Override
69      public int[] getDefaultTokens() {
70          return getRequiredTokens();
71      }
72  
73      @Override
74      public int[] getAcceptableTokens() {
75          return getRequiredTokens();
76      }
77  
78      @Override
79      public int[] getRequiredTokens() {
80          return new int[] {TokenTypes.METHOD_DEF, };
81      }
82  
83      /**
84       * Setter to control if check should apply to package-private members.
85       *
86       * @param applyTo new value of the property.
87       * @propertySince 5.1
88       */
89      @Override
90      public final void setApplyToPackage(boolean applyTo) {
91          super.setApplyToPackage(applyTo);
92      }
93  
94      /**
95       * Setter to control if check should apply to private members.
96       *
97       * @param applyTo new value of the property.
98       * @propertySince 5.1
99       */
100     @Override
101     public final void setApplyToPrivate(boolean applyTo) {
102         super.setApplyToPrivate(applyTo);
103     }
104 
105     /**
106      * Setter to control if check should apply to protected members.
107      *
108      * @param applyTo new value of the property.
109      * @propertySince 5.1
110      */
111     @Override
112     public final void setApplyToProtected(boolean applyTo) {
113         super.setApplyToProtected(applyTo);
114     }
115 
116     /**
117      * Setter to control if check should apply to public members.
118      *
119      * @param applyTo new value of the property.
120      * @propertySince 5.1
121      */
122     @Override
123     public final void setApplyToPublic(boolean applyTo) {
124         super.setApplyToPublic(applyTo);
125     }
126 
127     @Override
128     public void visitToken(DetailAST ast) {
129         if (!AnnotationUtil.hasOverrideAnnotation(ast)) {
130             // Will check the name against the format.
131             super.visitToken(ast);
132         }
133 
134         if (!allowClassName) {
135             // in all cases this will be the classDef type except anon inner
136             // with anon inner classes this will be the Literal_New keyword
137             final DetailAST classDefOrNew = ast.getParent().getParent();
138 
139             if (classDefOrNew != null) {
140                 final DetailAST method = ast.findFirstToken(TokenTypes.IDENT);
141                 final DetailAST classIdent =
142                     classDefOrNew.findFirstToken(TokenTypes.IDENT);
143                 // Following logic is to handle when a classIdent can not be
144                 // found. This is when you have a Literal_New keyword followed
145                 // a DOT, which is when you have:
146                 // new Outclass.InnerInterface(x) { ... }
147                 // Such a rare case, will not have the logic to handle parsing
148                 // down the tree looking for the first ident.
149                 if (classIdent != null
150                     && method.getText().equals(classIdent.getText())) {
151                     log(method, MSG_KEY, method.getText());
152                 }
153             }
154         }
155     }
156 
157     /**
158      * Setter to control whether to allow a method name to have the same name
159      * as the enclosing class name. Setting this property {@code false}
160      * helps to avoid confusion between constructors and methods.
161      *
162      * @param allowClassName true to allow false to disallow
163      * @since 5.0
164      */
165     public void setAllowClassName(boolean allowClassName) {
166         this.allowClassName = allowClassName;
167     }
168 
169 }