001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2025 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.naming;
021
022import com.puppycrawl.tools.checkstyle.api.DetailAST;
023import com.puppycrawl.tools.checkstyle.api.TokenTypes;
024import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
025
026/**
027 * <div>
028 * Checks that method names conform to a specified pattern.
029 * </div>
030 *
031 * <p>Also, checks if a method name has the same name as the residing class.
032 * The default is false (it is not allowed). It is legal in Java to have
033 * method with the same name as a class. As long as a return type is specified
034 * it is a method and not a constructor which it could be easily confused as.
035 * Does not check-style the name of an overridden methods because the developer does not
036 * have a choice in renaming such methods.
037 * </p>
038 *
039 * @since 3.0
040 */
041public class MethodNameCheck
042    extends AbstractAccessControlNameCheck {
043
044    /**
045     * A key is pointing to the warning message text in "messages.properties"
046     * file.
047     */
048    public static final String MSG_KEY = "method.name.equals.class.name";
049
050    /**
051     * Control whether to allow a method name to have the same name as the enclosing class name.
052     * Setting this property {@code false} helps to avoid confusion
053     * between constructors and methods.
054     */
055    private boolean allowClassName;
056
057    /** Creates a new {@code MethodNameCheck} instance. */
058    public MethodNameCheck() {
059        super("^[a-z][a-zA-Z0-9]*$");
060    }
061
062    @Override
063    public int[] getDefaultTokens() {
064        return getRequiredTokens();
065    }
066
067    @Override
068    public int[] getAcceptableTokens() {
069        return getRequiredTokens();
070    }
071
072    @Override
073    public int[] getRequiredTokens() {
074        return new int[] {TokenTypes.METHOD_DEF, };
075    }
076
077    /**
078     * Setter to control if check should apply to package-private members.
079     *
080     * @param applyTo new value of the property.
081     * @propertySince 5.1
082     */
083    @Override
084    public final void setApplyToPackage(boolean applyTo) {
085        super.setApplyToPackage(applyTo);
086    }
087
088    /**
089     * Setter to control if check should apply to private members.
090     *
091     * @param applyTo new value of the property.
092     * @propertySince 5.1
093     */
094    @Override
095    public final void setApplyToPrivate(boolean applyTo) {
096        super.setApplyToPrivate(applyTo);
097    }
098
099    /**
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}