Warning Avoid using implementation types such as "HashMap"; use interface instead

I get this warning from Sonar:

Avoid using implementation types like "HashMap"; use interface instead

What does it mean?

The class in which I receive this warning looks like this:

class A { private HashMap<String, String> map=new HashMap<String, String>(); //getters and setters } 

Please, I need the right solution to avoid the sonar warning.

+4
source share
3 answers

You should always specify an interface. i.e. in this case you should declare your field as follows:

 private Map<String, String> map= new HashMap<String, String>(); 

Thus, everything that uses the map variable will refer to it as a type of map , and not to a HashMap .

This allows you to change the base implementation of your map later without changing any code. You are no longer attached to HashMap

Read this question: What does โ€œinterface programmingโ€ mean?

Also, I'm not sure if you cast on Set there?

+14
source

I do not use Sonar, but basically it means

Always program the interface, not the emplemnetation class

 private Map<String, String> map= new HashMap<String, String>(); Interface Implementing class 
+3
source

Generally, you should always implement an interface instead of a specific type. In this example, this means that you must write your code as follows:

 private Map<String, String> map= new HashMap<String, String>(); 

The big advantage is that subsequently you can always change the specific implementation of your Card without breaking the code.

For more information on this, check out this question: What do programmers mean when they say, "Code versus interface, not object." ?

+3
source

All Articles