2021-04-28 16:49:39 +02:00
Non-static initializers are rarely used, and can be confusing for most developers because they only run when new class instances are created. When possible, non-static initializers should be refactored into standard constructors or field initializers.
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<String, String>() {
// Noncompliant - HashMap should be extended only to add behavior, not for initialization
{
put("a", "b");
}
};
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<String, String>();
static {
MY_MAP.put("a", "b");
}
}
----
or using Java 9 ``++Map.of++``:
----
class MyClass {
// Compliant
private static final Map<String, String> MY_MAP = java.util.Map.of("a", "b");
}
----
or using Guava:
----
class MyClass {
// Compliant
private static final Map<String, String> MY_MAP = ImmutableMap.of("a", "b");
}
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]