rspec/rules/S1171/java/rule.adoc
2024-02-27 15:24:58 +00:00

106 lines
2.9 KiB
Plaintext

== Why is this an issue?
Non-static initializers, also known as instance initializers, are blocks of code within a class that are executed when an instance of the
class is created. They are executed when an object of the class is created just before the constructor is called.
Non-static initializers are useful when you want to perform some common initialization logic for all objects of a class. They allow you to
initialize instance variables in a concise and centralized manner, without having to repeat the same initialization code in each constructor.
While non-static initializers may have some limited use cases, they are rarely used and can be confusing for most developers because they
only run when new class instances are created.
== How to fix it
Non-static initializers should be refactored into standard constructors or field initializers when possible.
In most cases, the use of constructors, overloaded constructors, or factory methods is preferable for initializing instance variables.
These approaches provide more explicit and controlled initialization, separate concerns, allow for better error handling, and make the code
easier to understand and maintain.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<String, String>() {
{
put("a", "b");
}
}; // Noncompliant - HashMap should be extended only to add behavior, not for initialization
}
----
==== Compliant solution
Using static initialization block:
[source,java,diff-id=1,diff-type=compliant]
----
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<>();
static {
MY_MAP.put("a", "b"); // Compliant
}
}
----
or using constructor:
[source,java]
----
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<>();
public MyClass() {
MY_MAP.put("a", "b"); // Compliant
}
}
----
or using Java 9 `Map.of`:
[source,java]
----
class MyClass {
private static final Map<String, String> MY_MAP = java.util.Map.of("a", "b"); // Compliant
}
----
or using Guava `ImmutableMap.of`:
[source,java]
----
class MyClass {
private static final Map<String, String> MY_MAP = com.google.common.collect.ImmutableMap.of("a", "b"); // Compliant
}
----
== Resources
=== Articles & blog posts
* https://www.baeldung.com/java-static-instance-initializer-blocks[Static vs. Instance Initializer Block in Java]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Move the contents of this initializer to a standard constructor or to field initializers.
'''
== Comments And Links
(visible only on this page)
=== is duplicated by: S3476
=== on 31 Jul 2013, 14:43:50 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-260
endif::env-github,rspecator-view[]