001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.Arrays;
023import java.util.List;
024import java.util.function.Predicate;
025
026import com.puppycrawl.tools.checkstyle.StatelessCheck;
027import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
031
032/**
033 * <p>
034 * Detects double brace initialization.
035 * </p>
036 * <p>
037 * Rationale: Double brace initialization (set of
038 * <a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.6">
039 * Instance Initializers</a> in class body) may look cool, but it is considered as anti-pattern
040 * and should be avoided.
041 * This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is
042 * returned outside and other object(s) hold reference to it.
043 * Created anonymous class is not static, it holds an implicit reference to the outer class
044 * instance.
045 * See this
046 * <a href="https://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/">
047 * blog post</a> and
048 * <a href="https://www.baeldung.com/java-double-brace-initialization">
049 * article</a> for more details.
050 * Check ignores any comments and semicolons in class body.
051 * </p>
052 * <p>
053 * To configure the check:
054 * </p>
055 * <pre>
056 * &lt;module name=&quot;AvoidDoubleBraceInitialization&quot;/&gt;
057 * </pre>
058 * <p>
059 * Which results in the following violations:
060 * </p>
061 * <pre>
062 * class MyClass {
063 *     List&lt;Integer&gt; list1 = new ArrayList&lt;&gt;() { // violation
064 *         {
065 *             add(1);
066 *         }
067 *     };
068 *     List&lt;String&gt; list2 = new ArrayList&lt;&gt;() { // violation
069 *         ;
070 *         // comments and semicolons are ignored
071 *         {
072 *             add("foo");
073 *         }
074 *     };
075 * }
076 * </pre>
077 * <p>
078 * Check only looks for double brace initialization and it ignores cases
079 * where the anonymous class has fields or methods.
080 * Though these might create the same memory issues as double brace,
081 * the extra class members can produce side effects if changed incorrectly.
082 * </p>
083 * <pre>
084 * class MyClass {
085 *     List&lt;Object&gt; list = new ArrayList&lt;&gt;() { // OK, not pure double brace pattern
086 *         private int field;
087 *         {
088 *             add(new Object());
089 *         }
090 *     };
091 * }
092 * </pre>
093 * <p>
094 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
095 * </p>
096 * <p>
097 * Violation Message Keys:
098 * </p>
099 * <ul>
100 * <li>
101 * {@code avoid.double.brace.init}
102 * </li>
103 * </ul>
104 *
105 * @since 8.30
106 */
107@StatelessCheck
108public class AvoidDoubleBraceInitializationCheck extends AbstractCheck {
109
110    /**
111     * A key is pointing to the warning message text in "messages.properties"
112     * file.
113     */
114    public static final String MSG_KEY = "avoid.double.brace.init";
115
116    /**
117     * List of token types that are used in {@link #HAS_MEMBERS} predicate.
118     */
119    private static final List<Integer> IGNORED_TYPES = Arrays.asList(
120        TokenTypes.INSTANCE_INIT,
121        TokenTypes.SEMI,
122        TokenTypes.LCURLY,
123        TokenTypes.RCURLY
124    );
125
126    /**
127     * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}.
128     */
129    private static final Predicate<DetailAST> HAS_MEMBERS =
130        token -> !IGNORED_TYPES.contains(token.getType());
131
132    @Override
133    public int[] getDefaultTokens() {
134        return getRequiredTokens();
135    }
136
137    @Override
138    public int[] getAcceptableTokens() {
139        return getRequiredTokens();
140    }
141
142    @Override
143    public int[] getRequiredTokens() {
144        return new int[] {TokenTypes.OBJBLOCK};
145    }
146
147    @Override
148    public void visitToken(DetailAST ast) {
149        if (ast.getParent().getType() == TokenTypes.LITERAL_NEW
150            && hasOnlyInitialization(ast)) {
151            log(ast, MSG_KEY);
152        }
153    }
154
155    /**
156     * Checks that block has at least one instance init block and no other class members.
157     *
158     * @param objBlock token to check
159     * @return true if there is least one instance init block and no other class members,
160     *     false otherwise
161     */
162    private static boolean hasOnlyInitialization(DetailAST objBlock) {
163        final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null;
164        return hasInitBlock
165                  && !TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isPresent();
166    }
167}