View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 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   * <p>
33   * Detects double brace initialization.
34   * </p>
35   * <p>
36   * Rationale: Double brace initialization (set of
37   * <a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.6">
38   * Instance Initializers</a> in class body) may look cool, but it is considered as anti-pattern
39   * and should be avoided.
40   * This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is
41   * returned outside and other object(s) hold reference to it.
42   * Created anonymous class is not static, it holds an implicit reference to the outer class
43   * instance.
44   * See this
45   * <a href="https://blog.jooq.org/dont-be-clever-the-double-curly-braces-anti-pattern/">
46   * blog post</a> and
47   * <a href="https://www.baeldung.com/java-double-brace-initialization">
48   * article</a> for more details.
49   * Check ignores any comments and semicolons in class body.
50   * </p>
51   * <p>
52   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
53   * </p>
54   * <p>
55   * Violation Message Keys:
56   * </p>
57   * <ul>
58   * <li>
59   * {@code avoid.double.brace.init}
60   * </li>
61   * </ul>
62   *
63   * @since 8.30
64   */
65  @StatelessCheck
66  public class AvoidDoubleBraceInitializationCheck extends AbstractCheck {
67  
68      /**
69       * A key is pointing to the warning message text in "messages.properties"
70       * file.
71       */
72      public static final String MSG_KEY = "avoid.double.brace.init";
73  
74      /**
75       * Set of token types that are used in {@link #HAS_MEMBERS} predicate.
76       */
77      private static final BitSet IGNORED_TYPES = TokenUtil.asBitSet(
78          TokenTypes.INSTANCE_INIT,
79          TokenTypes.SEMI,
80          TokenTypes.LCURLY,
81          TokenTypes.RCURLY
82      );
83  
84      /**
85       * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}.
86       */
87      private static final Predicate<DetailAST> HAS_MEMBERS =
88          token -> !IGNORED_TYPES.get(token.getType());
89  
90      @Override
91      public int[] getDefaultTokens() {
92          return getRequiredTokens();
93      }
94  
95      @Override
96      public int[] getAcceptableTokens() {
97          return getRequiredTokens();
98      }
99  
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 }