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