From b718196f79c89c76dc638864305e1ce51ec7aebe Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sun, 15 Aug 2021 08:15:01 +0100 Subject: [PATCH] Add AvoidDoubleBraceInitialization commit-id:c25380aa --- builder/src/main/resources/application.yml | 7 +++++ .../rules/AvoidDoubleBraceInitialization.md | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 builder/src/main/resources/rules/AvoidDoubleBraceInitialization.md diff --git a/builder/src/main/resources/application.yml b/builder/src/main/resources/application.yml index c9ce6aa..c37c3fb 100644 --- a/builder/src/main/resources/application.yml +++ b/builder/src/main/resources/application.yml @@ -1580,3 +1580,10 @@ rules: enabled: true source: CHECKSTYLE uri: https://checkstyle.sourceforge.io/config_coding.html#UnnecessarySemicolonAfterOuterTypeDeclaration + - + name: AvoidDoubleBraceInitialization + parent: TREEWALKER + level: LAYOUT + enabled: true + source: CHECKSTYLE + uri: https://checkstyle.sourceforge.io/config_coding.html#AvoidDoubleBraceInitialization diff --git a/builder/src/main/resources/rules/AvoidDoubleBraceInitialization.md b/builder/src/main/resources/rules/AvoidDoubleBraceInitialization.md new file mode 100644 index 0000000..4c755d8 --- /dev/null +++ b/builder/src/main/resources/rules/AvoidDoubleBraceInitialization.md @@ -0,0 +1,31 @@ + +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](https://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/) +and +[article](https://www.baeldung.com/java-double-brace-initialization) +for more details. Check ignores any comments and semicolons in class body. + +Invalid: +````java +class MyClass { + List list1 = new ArrayList<>() { // violation + { + add(1); + } + }; + List list2 = new ArrayList<>() { // violation + ; + // comments and semicolons are ignored + { + add("foo"); + } + }; +} +````