org.sonar.l10n.java.rules.squid.S1171.html Maven / Gradle / Ivy
Non-static initializers are rarely used, and can be confusing for most developers.
When possible, they should be refactored into standard constructors or field initializers.
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");
}
};
}
Compliant Solution
class MyClass {
private static final Map<String, String> MY_MAP = new HashMap<String, String>();
static {
MY_MAP.put("a", "b");
}
}
or using Guava:
class MyClass {
// Compliant
private static final Map<String, String> MY_MAP = ImmutableMap.of("a", "b");
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy