001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2014 Oliver Burn 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//////////////////////////////////////////////////////////////////////////////// 019package com.puppycrawl.tools.checkstyle.checks.coding; 020 021import com.puppycrawl.tools.checkstyle.api.Check; 022import com.puppycrawl.tools.checkstyle.api.TokenTypes; 023import com.puppycrawl.tools.checkstyle.api.DetailAST; 024 025/** 026 * <p> 027 * Checks for overly complicated boolean expressions. Currently finds code like 028 * <code>if (b == true)</code>, <code>b || true</code>, <code>!false</code>, 029 * etc. 030 * </p> 031 * <p> 032 * Rationale: Complex boolean logic makes code hard to understand and maintain. 033 * </p> 034 * <p> 035 * An example of how to configure the check is: 036 * </p> 037 * <pre> 038 * <module name="SimplifyBooleanExpression"/> 039 * </pre> 040 * @author lkuehne 041 */ 042public class SimplifyBooleanExpressionCheck 043 extends Check 044{ 045 @Override 046 public int[] getDefaultTokens() 047 { 048 return new int[] {TokenTypes.LITERAL_TRUE, TokenTypes.LITERAL_FALSE}; 049 } 050 051 @Override 052 public int[] getAcceptableTokens() 053 { 054 // Return empty list to prevent user changing tokens in the 055 // configuration. 056 return new int[] {}; 057 } 058 059 @Override 060 public int[] getRequiredTokens() 061 { 062 return new int[] {TokenTypes.LITERAL_TRUE, TokenTypes.LITERAL_FALSE}; 063 } 064 065 @Override 066 public void visitToken(DetailAST ast) 067 { 068 final DetailAST parent = ast.getParent(); 069 switch (parent.getType()) { 070 case TokenTypes.NOT_EQUAL: 071 case TokenTypes.EQUAL: 072 case TokenTypes.LNOT: 073 case TokenTypes.LOR: 074 case TokenTypes.LAND: 075 log(parent.getLineNo(), parent.getColumnNo(), 076 "simplify.expression"); 077 break; 078 default: 079 break; 080 } 081 } 082}