001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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.design;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026
027/**
028 * Make sure that utility classes (classes that contain only static methods)
029 * do not have a public constructor.
030 * <p>
031 * Rationale: Instantiating utility classes does not make sense.
032 * A common mistake is forgetting to hide the default constructor.
033 * </p>
034 *
035 */
036@StatelessCheck
037public class HideUtilityClassConstructorCheck extends AbstractCheck {
038
039    /**
040     * A key is pointing to the warning message text in "messages.properties"
041     * file.
042     */
043    public static final String MSG_KEY = "hide.utility.class";
044
045    @Override
046    public int[] getDefaultTokens() {
047        return getRequiredTokens();
048    }
049
050    @Override
051    public int[] getAcceptableTokens() {
052        return getRequiredTokens();
053    }
054
055    @Override
056    public int[] getRequiredTokens() {
057        return new int[] {TokenTypes.CLASS_DEF};
058    }
059
060    @Override
061    public void visitToken(DetailAST ast) {
062        // abstract class could not have private constructor
063        if (!isAbstract(ast)) {
064            final boolean hasStaticModifier = isStatic(ast);
065
066            final Details details = new Details(ast);
067            details.invoke();
068
069            final boolean hasDefaultCtor = details.isHasDefaultCtor();
070            final boolean hasPublicCtor = details.isHasPublicCtor();
071            final boolean hasNonStaticMethodOrField = details.isHasNonStaticMethodOrField();
072            final boolean hasNonPrivateStaticMethodOrField =
073                    details.isHasNonPrivateStaticMethodOrField();
074
075            final boolean hasAccessibleCtor = hasDefaultCtor || hasPublicCtor;
076
077            // figure out if class extends java.lang.object directly
078            // keep it simple for now and get a 99% solution
079            final boolean extendsJlo =
080                ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE) == null;
081
082            final boolean isUtilClass = extendsJlo
083                && !hasNonStaticMethodOrField && hasNonPrivateStaticMethodOrField;
084
085            if (isUtilClass && hasAccessibleCtor && !hasStaticModifier) {
086                log(ast, MSG_KEY);
087            }
088        }
089    }
090
091    /**
092     * Returns true if given class is abstract or false.
093     * @param ast class definition for check.
094     * @return true if a given class declared as abstract.
095     */
096    private static boolean isAbstract(DetailAST ast) {
097        return ast.findFirstToken(TokenTypes.MODIFIERS)
098            .findFirstToken(TokenTypes.ABSTRACT) != null;
099    }
100
101    /**
102     * Returns true if given class is static or false.
103     * @param ast class definition for check.
104     * @return true if a given class declared as static.
105     */
106    private static boolean isStatic(DetailAST ast) {
107        return ast.findFirstToken(TokenTypes.MODIFIERS)
108            .findFirstToken(TokenTypes.LITERAL_STATIC) != null;
109    }
110
111    /**
112     * Details of class that are required for validation.
113     */
114    private static class Details {
115
116        /** Class ast. */
117        private final DetailAST ast;
118        /** Result of details gathering. */
119        private boolean hasNonStaticMethodOrField;
120        /** Result of details gathering. */
121        private boolean hasNonPrivateStaticMethodOrField;
122        /** Result of details gathering. */
123        private boolean hasDefaultCtor;
124        /** Result of details gathering. */
125        private boolean hasPublicCtor;
126
127        /**
128         * C-tor.
129         * @param ast class ast
130         * */
131        Details(DetailAST ast) {
132            this.ast = ast;
133        }
134
135        /**
136         * Getter.
137         * @return boolean
138         */
139        public boolean isHasNonStaticMethodOrField() {
140            return hasNonStaticMethodOrField;
141        }
142
143        /**
144         * Getter.
145         * @return boolean
146         */
147        public boolean isHasNonPrivateStaticMethodOrField() {
148            return hasNonPrivateStaticMethodOrField;
149        }
150
151        /**
152         * Getter.
153         * @return boolean
154         */
155        public boolean isHasDefaultCtor() {
156            return hasDefaultCtor;
157        }
158
159        /**
160         * Getter.
161         * @return boolean
162         */
163        public boolean isHasPublicCtor() {
164            return hasPublicCtor;
165        }
166
167        /**
168         * Main method to gather statistics.
169         */
170        public void invoke() {
171            final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
172            hasNonStaticMethodOrField = false;
173            hasNonPrivateStaticMethodOrField = false;
174            hasDefaultCtor = true;
175            hasPublicCtor = false;
176            DetailAST child = objBlock.getFirstChild();
177
178            while (child != null) {
179                final int type = child.getType();
180                if (type == TokenTypes.METHOD_DEF
181                        || type == TokenTypes.VARIABLE_DEF) {
182                    final DetailAST modifiers =
183                        child.findFirstToken(TokenTypes.MODIFIERS);
184                    final boolean isStatic =
185                        modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
186
187                    if (isStatic) {
188                        final boolean isPrivate =
189                                modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null;
190
191                        if (!isPrivate) {
192                            hasNonPrivateStaticMethodOrField = true;
193                        }
194                    }
195                    else {
196                        hasNonStaticMethodOrField = true;
197                    }
198                }
199                if (type == TokenTypes.CTOR_DEF) {
200                    hasDefaultCtor = false;
201                    final DetailAST modifiers =
202                        child.findFirstToken(TokenTypes.MODIFIERS);
203                    if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null
204                        && modifiers.findFirstToken(TokenTypes.LITERAL_PROTECTED) == null) {
205                        // treat package visible as public
206                        // for the purpose of this Check
207                        hasPublicCtor = true;
208                    }
209                }
210                child = child.getNextSibling();
211            }
212        }
213
214    }
215
216}