1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2019 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.design;
21  
22  import com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  
27  /**
28   * <p>
29   * Restricts throws statements to a specified count (default = 4).
30   * Methods with "Override" or "java.lang.Override" annotation are skipped
31   * from validation as current class cannot change signature of these methods.
32   * </p>
33   * <p>
34   * Rationale:
35   * Exceptions form part of a methods interface. Declaring
36   * a method to throw too many differently rooted
37   * exceptions makes exception handling onerous and leads
38   * to poor programming practices such as catch
39   * (Exception). 4 is the empirical value which is based
40   * on reports that we had for the ThrowsCountCheck over big projects
41   * such as OpenJDK. This check also forces developers to put exceptions
42   * into a hierarchy such that in the simplest
43   * case, only one type of exception need be checked for by
44   * a caller but allows any sub-classes to be caught
45   * specifically if necessary. For more information on rules
46   * for the exceptions and their issues, see Effective Java:
47   * Programming Language Guide Second Edition
48   * by Joshua Bloch pages 264-273.
49   * </p>
50   * <p>
51   * <b>ignorePrivateMethods</b> - allows to skip private methods as they do
52   * not cause problems for other classes.
53   * </p>
54   */
55  @StatelessCheck
56  public final class ThrowsCountCheck extends AbstractCheck {
57  
58      /**
59       * A key is pointing to the warning message text in "messages.properties"
60       * file.
61       */
62      public static final String MSG_KEY = "throws.count";
63  
64      /** Default value of max property. */
65      private static final int DEFAULT_MAX = 4;
66  
67      /** Whether private methods must be ignored. **/
68      private boolean ignorePrivateMethods = true;
69  
70      /** Maximum allowed throws statements. */
71      private int max;
72  
73      /** Creates new instance of the check. */
74      public ThrowsCountCheck() {
75          max = DEFAULT_MAX;
76      }
77  
78      @Override
79      public int[] getDefaultTokens() {
80          return getRequiredTokens();
81      }
82  
83      @Override
84      public int[] getRequiredTokens() {
85          return new int[] {
86              TokenTypes.LITERAL_THROWS,
87          };
88      }
89  
90      @Override
91      public int[] getAcceptableTokens() {
92          return getRequiredTokens();
93      }
94  
95      /**
96       * Sets whether private methods must be ignored.
97       * @param ignorePrivateMethods whether private methods must be ignored.
98       */
99      public void setIgnorePrivateMethods(boolean ignorePrivateMethods) {
100         this.ignorePrivateMethods = ignorePrivateMethods;
101     }
102 
103     /**
104      * Setter for max property.
105      * @param max maximum allowed throws statements.
106      */
107     public void setMax(int max) {
108         this.max = max;
109     }
110 
111     @Override
112     public void visitToken(DetailAST ast) {
113         if (ast.getType() == TokenTypes.LITERAL_THROWS) {
114             visitLiteralThrows(ast);
115         }
116         else {
117             throw new IllegalStateException(ast.toString());
118         }
119     }
120 
121     /**
122      * Checks number of throws statements.
123      * @param ast throws for check.
124      */
125     private void visitLiteralThrows(DetailAST ast) {
126         if ((!ignorePrivateMethods || !isInPrivateMethod(ast))
127                 && !isOverriding(ast)) {
128             // Account for all the commas!
129             final int count = (ast.getChildCount() + 1) / 2;
130             if (count > max) {
131                 log(ast, MSG_KEY, count, max);
132             }
133         }
134     }
135 
136     /**
137      * Check if a method has annotation @Override.
138      * @param ast throws, which is being checked.
139      * @return true, if a method has annotation @Override.
140      */
141     private static boolean isOverriding(DetailAST ast) {
142         final DetailAST modifiers = ast.getParent().findFirstToken(TokenTypes.MODIFIERS);
143         boolean isOverriding = false;
144         DetailAST child = modifiers.getFirstChild();
145         while (child != null) {
146             if (child.getType() == TokenTypes.ANNOTATION
147                     && "Override".equals(getAnnotationName(child))) {
148                 isOverriding = true;
149                 break;
150             }
151             child = child.getNextSibling();
152         }
153         return isOverriding;
154     }
155 
156     /**
157      * Gets name of an annotation.
158      * @param annotation to get name of.
159      * @return name of an annotation.
160      */
161     private static String getAnnotationName(DetailAST annotation) {
162         final DetailAST dotAst = annotation.findFirstToken(TokenTypes.DOT);
163         final String name;
164         if (dotAst == null) {
165             name = annotation.findFirstToken(TokenTypes.IDENT).getText();
166         }
167         else {
168             name = dotAst.findFirstToken(TokenTypes.IDENT).getText();
169         }
170         return name;
171     }
172 
173     /**
174      * Checks if method, which throws an exception is private.
175      * @param ast throws, which is being checked.
176      * @return true, if method, which throws an exception is private.
177      */
178     private static boolean isInPrivateMethod(DetailAST ast) {
179         final DetailAST methodModifiers = ast.getParent().findFirstToken(TokenTypes.MODIFIERS);
180         return methodModifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null;
181     }
182 
183 }