Coverage Report - com.puppycrawl.tools.checkstyle.checks.design.MutableExceptionCheck
 
Classes in this File Line Coverage Branch Coverage Complexity
MutableExceptionCheck
100%
44/44
100%
19/19
1.833
 
 1  
 ////////////////////////////////////////////////////////////////////////////////
 2  
 // checkstyle: Checks Java source code for adherence to a set of rules.
 3  
 // Copyright (C) 2001-2017 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 java.util.ArrayDeque;
 23  
 import java.util.Deque;
 24  
 import java.util.regex.Pattern;
 25  
 
 26  
 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
 27  
 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
 28  
 import com.puppycrawl.tools.checkstyle.api.DetailAST;
 29  
 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
 30  
 
 31  
 /**
 32  
  * <p> Ensures that exceptions (classes with names conforming to some regular
 33  
  * expression and explicitly extending classes with names conforming to other
 34  
  * regular expression) are immutable. That is, they have only final fields.</p>
 35  
  * <p> Rationale: Exception instances should represent an error
 36  
  * condition. Having non final fields not only allows the state to be
 37  
  * modified by accident and therefore mask the original condition but
 38  
  * also allows developers to accidentally forget to initialise state
 39  
  * thereby leading to code catching the exception to draw incorrect
 40  
  * conclusions based on the state.</p>
 41  
  *
 42  
  * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
 43  
  */
 44  
 @FileStatefulCheck
 45  14
 public final class MutableExceptionCheck extends AbstractCheck {
 46  
 
 47  
     /**
 48  
      * A key is pointing to the warning message text in "messages.properties"
 49  
      * file.
 50  
      */
 51  
     public static final String MSG_KEY = "mutable.exception";
 52  
 
 53  
     /** Default value for format and extendedClassNameFormat properties. */
 54  
     private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$|^.*Throwable$";
 55  
     /** Stack of checking information for classes. */
 56  14
     private final Deque<Boolean> checkingStack = new ArrayDeque<>();
 57  
     /** Pattern for class name that is being extended. */
 58  14
     private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT);
 59  
     /** Should we check current class or not. */
 60  
     private boolean checking;
 61  
     /** The regexp to match against. */
 62  14
     private Pattern format = Pattern.compile(DEFAULT_FORMAT);
 63  
 
 64  
     /**
 65  
      * Sets the format of extended class name to the specified regular expression.
 66  
      * @param extendedClassNameFormat a {@code String} value
 67  
      */
 68  
     public void setExtendedClassNameFormat(Pattern extendedClassNameFormat) {
 69  1
         this.extendedClassNameFormat = extendedClassNameFormat;
 70  1
     }
 71  
 
 72  
     /**
 73  
      * Set the format for the specified regular expression.
 74  
      * @param pattern the new pattern
 75  
      */
 76  
     public void setFormat(Pattern pattern) {
 77  1
         format = pattern;
 78  1
     }
 79  
 
 80  
     @Override
 81  
     public int[] getDefaultTokens() {
 82  33
         return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
 83  
     }
 84  
 
 85  
     @Override
 86  
     public int[] getRequiredTokens() {
 87  17
         return getDefaultTokens();
 88  
     }
 89  
 
 90  
     @Override
 91  
     public int[] getAcceptableTokens() {
 92  5
         return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF};
 93  
     }
 94  
 
 95  
     @Override
 96  
     public void visitToken(DetailAST ast) {
 97  67
         switch (ast.getType()) {
 98  
             case TokenTypes.CLASS_DEF:
 99  31
                 visitClassDef(ast);
 100  31
                 break;
 101  
             case TokenTypes.VARIABLE_DEF:
 102  35
                 visitVariableDef(ast);
 103  35
                 break;
 104  
             default:
 105  1
                 throw new IllegalStateException(ast.toString());
 106  
         }
 107  66
     }
 108  
 
 109  
     @Override
 110  
     public void leaveToken(DetailAST ast) {
 111  66
         if (ast.getType() == TokenTypes.CLASS_DEF) {
 112  31
             leaveClassDef();
 113  
         }
 114  66
     }
 115  
 
 116  
     /**
 117  
      * Called when we start processing class definition.
 118  
      * @param ast class definition node
 119  
      */
 120  
     private void visitClassDef(DetailAST ast) {
 121  31
         checkingStack.push(checking);
 122  31
         checking = isNamedAsException(ast) && isExtendedClassNamedAsException(ast);
 123  31
     }
 124  
 
 125  
     /** Called when we leave class definition. */
 126  
     private void leaveClassDef() {
 127  31
         checking = checkingStack.pop();
 128  31
     }
 129  
 
 130  
     /**
 131  
      * Checks variable definition.
 132  
      * @param ast variable def node for check
 133  
      */
 134  
     private void visitVariableDef(DetailAST ast) {
 135  35
         if (checking && ast.getParent().getType() == TokenTypes.OBJBLOCK) {
 136  12
             final DetailAST modifiersAST =
 137  12
                 ast.findFirstToken(TokenTypes.MODIFIERS);
 138  
 
 139  12
             if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) {
 140  18
                 log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY,
 141  9
                         ast.findFirstToken(TokenTypes.IDENT).getText());
 142  
             }
 143  
         }
 144  35
     }
 145  
 
 146  
     /**
 147  
      * Checks that a class name conforms to specified format.
 148  
      * @param ast class definition node
 149  
      * @return true if a class name conforms to specified format
 150  
      */
 151  
     private boolean isNamedAsException(DetailAST ast) {
 152  31
         final String className = ast.findFirstToken(TokenTypes.IDENT).getText();
 153  31
         return format.matcher(className).find();
 154  
     }
 155  
 
 156  
     /**
 157  
      * Checks that if extended class name conforms to specified format.
 158  
      * @param ast class definition node
 159  
      * @return true if extended class name conforms to specified format
 160  
      */
 161  
     private boolean isExtendedClassNamedAsException(DetailAST ast) {
 162  15
         boolean result = false;
 163  15
         final DetailAST extendsClause = ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE);
 164  15
         if (extendsClause != null) {
 165  11
             DetailAST currentNode = extendsClause;
 166  27
             while (currentNode.getLastChild() != null) {
 167  16
                 currentNode = currentNode.getLastChild();
 168  
             }
 169  11
             final String extendedClassName = currentNode.getText();
 170  11
             result = extendedClassNameFormat.matcher(extendedClassName).matches();
 171  
         }
 172  15
         return result;
 173  
     }
 174  
 }