rspec/rules/S3476/java/rule.adoc

37 lines
1003 B
Plaintext
Raw Normal View History

When you need to perform a complicated initialization of a ``++static++`` member, it should be done in a ``++static++`` initializer block. That's because such blocks are only executed when the class is loaded into the JVM. That is, they run only once, and that happens before any instances are created. Non-``++static++`` blocks, on the other hand, run once for each instance that's created, so any ``++static++`` members "initialized" in such a block will be re-set for each new instance.
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
----
public class MyClass {
private static List<String> names = new ArrayList<>();
{
names.add("foo"); // Noncompliant
}
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
----
public class MyClass {
private static List<String> names = new ArrayList<>();
static {
names.add("foo");
}
----
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]