rspec/rules/S1171/java/rule.adoc

68 lines
1.3 KiB
Plaintext
Raw Normal View History

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 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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++``:
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class MyClass {
// Compliant
private static final Map<String, String> MY_MAP = java.util.Map.of("a", "b");
}
----
or using Guava:
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class MyClass {
// Compliant
private static final Map<String, String> MY_MAP = ImmutableMap.of("a", "b");
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]