001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2023 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 * To configure the check: 053 * </p> 054 * <pre> 055 * <module name="AvoidDoubleBraceInitialization"/> 056 * </pre> 057 * <p> 058 * Which results in the following violations: 059 * </p> 060 * <pre> 061 * class MyClass { 062 * List<Integer> list1 = new ArrayList<>() { // violation 063 * { 064 * add(1); 065 * } 066 * }; 067 * List<String> list2 = new ArrayList<>() { // violation 068 * ; 069 * // comments and semicolons are ignored 070 * { 071 * add("foo"); 072 * } 073 * }; 074 * } 075 * </pre> 076 * <p> 077 * Check only looks for double brace initialization and it ignores cases 078 * where the anonymous class has fields or methods. 079 * Though these might create the same memory issues as double brace, 080 * the extra class members can produce side effects if changed incorrectly. 081 * </p> 082 * <pre> 083 * class MyClass { 084 * List<Object> list = new ArrayList<>() { // OK, not pure double brace pattern 085 * private int field; 086 * { 087 * add(new Object()); 088 * } 089 * }; 090 * } 091 * </pre> 092 * <p> 093 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 094 * </p> 095 * <p> 096 * Violation Message Keys: 097 * </p> 098 * <ul> 099 * <li> 100 * {@code avoid.double.brace.init} 101 * </li> 102 * </ul> 103 * 104 * @since 8.30 105 */ 106@StatelessCheck 107public class AvoidDoubleBraceInitializationCheck extends AbstractCheck { 108 109 /** 110 * A key is pointing to the warning message text in "messages.properties" 111 * file. 112 */ 113 public static final String MSG_KEY = "avoid.double.brace.init"; 114 115 /** 116 * Set of token types that are used in {@link #HAS_MEMBERS} predicate. 117 */ 118 private static final BitSet IGNORED_TYPES = TokenUtil.asBitSet( 119 TokenTypes.INSTANCE_INIT, 120 TokenTypes.SEMI, 121 TokenTypes.LCURLY, 122 TokenTypes.RCURLY 123 ); 124 125 /** 126 * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}. 127 */ 128 private static final Predicate<DetailAST> HAS_MEMBERS = 129 token -> !IGNORED_TYPES.get(token.getType()); 130 131 @Override 132 public int[] getDefaultTokens() { 133 return getRequiredTokens(); 134 } 135 136 @Override 137 public int[] getAcceptableTokens() { 138 return getRequiredTokens(); 139 } 140 141 @Override 142 public int[] getRequiredTokens() { 143 return new int[] {TokenTypes.OBJBLOCK}; 144 } 145 146 @Override 147 public void visitToken(DetailAST ast) { 148 if (ast.getParent().getType() == TokenTypes.LITERAL_NEW 149 && hasOnlyInitialization(ast)) { 150 log(ast, MSG_KEY); 151 } 152 } 153 154 /** 155 * Checks that block has at least one instance init block and no other class members. 156 * 157 * @param objBlock token to check 158 * @return true if there is least one instance init block and no other class members, 159 * false otherwise 160 */ 161 private static boolean hasOnlyInitialization(DetailAST objBlock) { 162 final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null; 163 return hasInitBlock 164 && TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isEmpty(); 165 } 166}