AvoidDoubleBraceInitialization

Since Checkstyle 8.30

Description

Detects double brace initialization.

Rationale: Double brace initialization (set of Instance Initializers in class body) may look cool, but it is considered as anti-pattern and should be avoided. This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is returned outside and other object(s) hold reference to it. Created anonymous class is not static, it holds an implicit reference to the outer class instance. See this blog post and article for more details. Check ignores any comments and semicolons in class body.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="AvoidDoubleBraceInitialization"/>
  </module>
</module>
        

Which results in the following violations:

class MyClass {
    List<Integer> list1 = new ArrayList<>() { // violation
        {
            add(1);
        }
    };
    List<String> list2 = new ArrayList<>() { // violation
        ;
        // comments and semicolons are ignored
        {
            add("foo");
        }
    };
}
        

Check only looks for double brace initialization and it ignores cases where the anonymous class has fields or methods. Though these might create the same memory issues as double brace, the extra class members can produce side effects if changed incorrectly.

class MyClass {
    List<Object> list = new ArrayList<>() { // OK, not pure double brace pattern
        private int field;
        {
            add(new Object());
        }
    };
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker