View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 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.coding;
21  
22  import java.util.BitSet;
23  import java.util.function.Predicate;
24  
25  import com.puppycrawl.tools.checkstyle.StatelessCheck;
26  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27  import com.puppycrawl.tools.checkstyle.api.DetailAST;
28  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
29  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
30  
31  /**
32   * <div>
33   * Detects double brace initialization.
34   * </div>
35   *
36   * <p>
37   * Rationale: Double brace initialization (set of
38   * <a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.6">
39   * Instance Initializers</a> in class body) may look cool, but it is considered as anti-pattern
40   * and should be avoided.
41   * This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is
42   * returned outside and other object(s) hold reference to it.
43   * Created anonymous class is not static, it holds an implicit reference to the outer class
44   * instance.
45   * See this
46   * <a href="https://blog.jooq.org/dont-be-clever-the-double-curly-braces-anti-pattern/">
47   * blog post</a> and
48   * <a href="https://www.baeldung.com/java-double-brace-initialization">
49   * article</a> for more details.
50   * Check ignores any comments and semicolons in class body.
51   * </p>
52   *
53   * @since 8.30
54   */
55  @StatelessCheck
56  public class AvoidDoubleBraceInitializationCheck extends AbstractCheck {
57  
58      /**
59       * A key is pointing to the warning message text in "messages.properties"
60       * file.
61       */
62      public static final String MSG_KEY = "avoid.double.brace.init";
63  
64      /**
65       * Set of token types that are used in {@link #HAS_MEMBERS} predicate.
66       */
67      private static final BitSet IGNORED_TYPES = TokenUtil.asBitSet(
68          TokenTypes.INSTANCE_INIT,
69          TokenTypes.SEMI,
70          TokenTypes.LCURLY,
71          TokenTypes.RCURLY
72      );
73  
74      /**
75       * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}.
76       */
77      private static final Predicate<DetailAST> HAS_MEMBERS =
78          token -> !IGNORED_TYPES.get(token.getType());
79  
80      @Override
81      public int[] getDefaultTokens() {
82          return getRequiredTokens();
83      }
84  
85      @Override
86      public int[] getAcceptableTokens() {
87          return getRequiredTokens();
88      }
89  
90      @Override
91      public int[] getRequiredTokens() {
92          return new int[] {TokenTypes.OBJBLOCK};
93      }
94  
95      @Override
96      public void visitToken(DetailAST ast) {
97          if (ast.getParent().getType() == TokenTypes.LITERAL_NEW
98              && hasOnlyInitialization(ast)) {
99              log(ast, MSG_KEY);
100         }
101     }
102 
103     /**
104      * Checks that block has at least one instance init block and no other class members.
105      *
106      * @param objBlock token to check
107      * @return true if there is least one instance init block and no other class members,
108      *     false otherwise
109      */
110     private static boolean hasOnlyInitialization(DetailAST objBlock) {
111         final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null;
112         return hasInitBlock
113                   && TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isEmpty();
114     }
115 }