rspec/rules/S3476/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

80 lines
1.7 KiB
Plaintext

== Why is this an issue?
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
[source,java]
----
public class MyClass {
private static List<String> names = new ArrayList<>();
{
names.add("foo"); // Noncompliant
}
----
=== Compliant solution
[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)
=== duplicates: S1171
=== on 14 Dec 2015, 10:46:39 Nicolas Peru wrote:
\[~ann.campbell.2] The rule examples do not match the title and descritption :
a static initiliazer has the following form :
----
static {
//some code
}
----
if you use this on an instance variable, code does not compile.
However the other way around will compile and is probably a mistake (using a non static initializer on a static variable) :
----
class A {
public static List<String> foo = new ArrayList<>();
{
foo.add("foo");
}
}
----
As this code will be executed for every instanciation of A.
=== on 14 Dec 2015, 20:00:17 Ann Campbell wrote:
Thanks [~nicolas.peru]. Look now.
=== on 15 Dec 2015, 14:10:41 Nicolas Peru wrote:
LGTM. Moving issue to java top as this is easy to achieve.
endif::env-github,rspecator-view[]