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;
024import antlr.collections.AST;
025
026/**
027 * <p>Checks that string literals are not used with
028 * <code>==</code> or <code>&#33;=</code>.
029 * </p>
030 * <p>
031 * Rationale: Novice Java programmers often use code like
032 * <code>if (x == &quot;something&quot;)</code> when they mean
033 * <code>if (&quot;something&quot;.equals(x))</code>.
034 * </p>
035 *
036 * @author Lars K&uuml;hne
037 */
038public class StringLiteralEqualityCheck extends Check
039{
040    @Override
041    public int[] getDefaultTokens()
042    {
043        return new int[] {TokenTypes.EQUAL, TokenTypes.NOT_EQUAL};
044    }
045
046    @Override
047    public void visitToken(DetailAST ast)
048    {
049        // no need to check for nulls here, == and != always have two children
050        final AST firstChild = ast.getFirstChild();
051        final AST secondChild = firstChild.getNextSibling();
052
053        if ((firstChild.getType() == TokenTypes.STRING_LITERAL)
054                || (secondChild.getType() == TokenTypes.STRING_LITERAL))
055        {
056            log(ast.getLineNo(), ast.getColumnNo(),
057                    "string.literal.equality", ast.getText());
058        }
059    }
060}