0

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 ?

Sunil
  • 71
  • 1
  • 11

1 Answers1

0

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.

Basti
  • 1,117
  • 12
  • 32
  • "Code" was posted as a screenshot because its the screen that the SonarLint Plugin displays for the selected rule. I was explaining how to use the Plugin, not giving any example code. Since that solves the issue plus potential similar issues for the future it seemed like the better info to provide. – Basti Oct 31 '20 at 13:27
  • Thanks for your response @Basti. Is there any difference using inner-loop in static block and assigning pairs ? Compared with what you have Suggested in code-snippet (General Case). – Sunil Oct 31 '20 at 14:13
  • 1
    @Sunil That is a question you should ask in a separate thread. I rarely use them so i don't know the mechanics behind it to well, so i don't feel confident answering that question without doing research on it first. – Basti Nov 01 '20 at 13:30
  • 1
    @GhostCat good point with the screen readers. I'll keep that in mind for the future. Thanks for pointing it out. – Basti Nov 01 '20 at 13:31