Sonar Error - Make this member "protected"

Viewed 8043

In the below class I am declaring myMap

public class AllMap {
    public static final Map<String, String> myMap= new HashMap<>();
    static {
        Map.put("yy", "AA");
        Map.put("xx", "BB");
    }
}

I need to access map in other class.

public class Test {
    FieldMap.Map;
}

Everything is working fine,but sonar is giving warning on 1st class:

Make this member "protected".

on the line

public static final Map<String, String> myMap = new HashMap<>();

Should I ignore this warning or should I change it to protected?

3 Answers

If you need to access the map in other classes, then you should protect it against modifications:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class AllMap {
    public static final Map<String, String> myMap;
    static {
        final Map<String, String> tmpMap = new HashMap<>();
        tmpMap.put("yy", "AA");
        tmpMap.put("xx", "BB");
        myMap = Collections.unmodifiableMap(tmpMap);
    }
}

You can still use it and SonarQube won't mark this as error (because the map is read-only).

Read more about Collections#unmodifiableMap(Map).

Sonar is giving you suggestion that your "member" which is:

public final Map<String, String> myMap = new HashMap<>();

should not be public.

Why?

Leaving this as public makes it available from any other package - so you are exposing the member to everybody. Below code is accessing the member directly:

AllMap allMap = new AllMap();
allMap.myMap.put("X", "Y");

In most cases members should be private and accessed by getters and setters, which could prevent with returning the same reference - so you can implement some logic before you get the reference or set it.

If you need to make it static, make static getters and setters.

Sonar lint issue because you are exposing references to mutable objects to client code.Here you are exposing a Map though it is final the final object allows clients to modify the contents of the object.

Never initialize such a field to a client-provided object reference or return the object reference from an accessor.

private static final SomeType [] THE_THINGS = { ... };
public static final List<SomeType> SOMETHINGS =
  Collections.unmodifiableList(Arrays.asList(THE_THINGS));

Reference link

Reference link2

Related