I am getting this warning on Sonar:
Avoid using implementation types like 'HashMap'; use the interface instead
What does it mean?
The class in which i get this warning is as:
class A {
private HashMap<String, String> map=new HashMap<String, String>();
//getters and setters
}
Please, I want proper solution to avoid warning on Sonar.
You should always code to an interface. ie. in this case you should declare your field like this:
private Map<String, String> map= new HashMap<String, String>();
This way anything using the map
variable will treat it as type Map
rather than HashMap
.
This allows you to swap out the underlying implementation of your map at a later date without having to change any code. You are no longer tied to HashMap
Read through this question: What does it mean to "program to an interface"?
Also I am not sure what you were doing casting to a Set
there?
I dont use Sonar, but what the warning basically means is
Always program to an interface rather than implemnetation class
private Map<String, String> map= new HashMap<String, String>();
Interface Implementing class
Generally, you should always implement against an interface instead of a concrete type. In this example it means you should write your code like that:
private Map<String, String> map= new HashMap<String, String>();
The big advantage is that you can then later always change the concrete implementation of your Map without breaking the code.
To get more details about it, check out this question: What do programmers mean when they say, "Code against an interface, not an object."?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With