Do not use Java double brace initialization
JavaClean code
Java double brace initialisation is an anti-pattern.
Cf. https://www.baeldung.com/java-double-brace-initialization
Disadvantages of using double braces are:
Obscure, not widely known way to do the initialization It creates an extra class every time we use it Doesn’t support the use of the “diamond operator” – a feature introduced in Java 7 Doesn’t work if the class we are trying to extend is marked final Holds a hidden reference to the enclosing instance, which may cause memory leaks
It’s due to these disadvantages that double brace initialization is considered as an anti-pattern.
Examples
Example 1:
Negative
Incorrect implementation that violates the practice.
public class Main {
public static void main(String[] args) {
Order order = new Order() {{
setReference("abc-123");
setCustomer("John Doe");
}};
}
}