001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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.coding;
021
022import java.util.BitSet;
023import java.util.function.Predicate;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
030
031/**
032 * <p>
033 * Detects double brace initialization.
034 * </p>
035 * <p>
036 * Rationale: Double brace initialization (set of
037 * <a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.6">
038 * Instance Initializers</a> in class body) may look cool, but it is considered as anti-pattern
039 * and should be avoided.
040 * This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is
041 * returned outside and other object(s) hold reference to it.
042 * Created anonymous class is not static, it holds an implicit reference to the outer class
043 * instance.
044 * See this
045 * <a href="https://blog.jooq.org/dont-be-clever-the-double-curly-braces-anti-pattern/">
046 * blog post</a> and
047 * <a href="https://www.baeldung.com/java-double-brace-initialization">
048 * article</a> for more details.
049 * Check ignores any comments and semicolons in class body.
050 * </p>
051 * <p>
052 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
053 * </p>
054 * <p>
055 * Violation Message Keys:
056 * </p>
057 * <ul>
058 * <li>
059 * {@code avoid.double.brace.init}
060 * </li>
061 * </ul>
062 *
063 * @since 8.30
064 */
065@StatelessCheck
066public class AvoidDoubleBraceInitializationCheck extends AbstractCheck {
067
068    /**
069     * A key is pointing to the warning message text in "messages.properties"
070     * file.
071     */
072    public static final String MSG_KEY = "avoid.double.brace.init";
073
074    /**
075     * Set of token types that are used in {@link #HAS_MEMBERS} predicate.
076     */
077    private static final BitSet IGNORED_TYPES = TokenUtil.asBitSet(
078        TokenTypes.INSTANCE_INIT,
079        TokenTypes.SEMI,
080        TokenTypes.LCURLY,
081        TokenTypes.RCURLY
082    );
083
084    /**
085     * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}.
086     */
087    private static final Predicate<DetailAST> HAS_MEMBERS =
088        token -> !IGNORED_TYPES.get(token.getType());
089
090    @Override
091    public int[] getDefaultTokens() {
092        return getRequiredTokens();
093    }
094
095    @Override
096    public int[] getAcceptableTokens() {
097        return getRequiredTokens();
098    }
099
100    @Override
101    public int[] getRequiredTokens() {
102        return new int[] {TokenTypes.OBJBLOCK};
103    }
104
105    @Override
106    public void visitToken(DetailAST ast) {
107        if (ast.getParent().getType() == TokenTypes.LITERAL_NEW
108            && hasOnlyInitialization(ast)) {
109            log(ast, MSG_KEY);
110        }
111    }
112
113    /**
114     * Checks that block has at least one instance init block and no other class members.
115     *
116     * @param objBlock token to check
117     * @return true if there is least one instance init block and no other class members,
118     *     false otherwise
119     */
120    private static boolean hasOnlyInitialization(DetailAST objBlock) {
121        final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null;
122        return hasInitBlock
123                  && TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isEmpty();
124    }
125}