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