Move the contents of this initializer to a standard constructor or to field initializers

3k Views Asked by At

As I installed Sonarlint plugin in my eclipse IDE, i got the above (Heading) Major Issue in Sonar Report.

The Code is:

public class Demo
{
public static final Map<String, String> CARD_TYPES;

static
    {
        CARD_TYPES = new HashMap<String, String>()
        {
            {  //Move the contents of this initializer to a standard constructor or to field* initializers
                put("visa", "001");
                put("diner", "002");
            }
        };
    }
//..code goes here
}

The Query is: what exactly should be done in above Static Block, to Resolve the above issue ?

1

There are 1 best solutions below

4
Basti On

Your code example seems to be altered for this post? Doesn't compile because CARD_TYPES is not declared anywhere. Also there is a * in front of the inline comment which shouldn't be there.

Regardless, in your SonarLint report you can select a specific issue. enter image description here which then allows you to see the details of the Rule that it is reporting this issue. enter image description here These descriptions also contain compliant and not compliant code examples to help you understand the issue. In your case a compliant solution would be. enter image description here Basically: initialize the map directly at the declaration. Then use the static context of the class to access and fill it, rather than the context of the map.