Why the coding should be “to the interface” especially for primitive datatypes?

╄→尐↘猪︶ㄣ 提交于 2019-12-25 00:52:41

问题


I have a doubt on the design methodology that why we implement the code to the interface. This is very much observed in primitive data types. Like I am not getting the difference between these two :

Map<Integer, String> mymap = new HashMap<Integer, String>(); 

And

HashMap<Integer, String> mymap = new HashMap<Integer, String>();

Is there any difference between these two? I mean each and every place where we are going to use mymap will remain same in both the cases.

I am sorry if the question seems to be of no use but I really not getting that how this is going to make any difference later on where mymap will be used. Please help?

Thanks..

Note - I have already seen this question on SO but it is not giving what I want.


回答1:


Because mymap can be instantiated somewhere else with a different implementation of Map, you should not rely on it being an instance of HashMap in the code using it.




回答2:


The second option limits you to always use HashMap, even if some day TreeMap could be more useful.

In the first one you can change the particular implementation easier - you only have to change one line of code. It's especially visible if you return your map from methods - the method return type doesn't have to change.

Coding to an interface also helps mocking the object during tests, but I assume that's not the case here.




回答3:


Using Map mymap allows you to change the implementation later. For example, if at some point you need mymap to be ordered, you just change the initialization to LinkedHashMap.




回答4:


If you are only using this inside your type (meaning: private) and instantiate it yourself, it doesn't make a real difference.

It starts getting interesting if the public interface of your type exposes a Map vs. a HashMap.




回答5:


In the specific instance you propose, it may not make a difference, but it's good practice to get yourself used to always use the interface in your declarations because there are legitimate instances where you will need that flexibility.




回答6:


The former allows you to change to:

Map<Integer, String> mymap = new TreeMap<Integer, String>(); 

for example, without breaking all the rest of your code.

A much more minor advantage is that your IDE can show you the methods for the interface, rather than the (potentially much larger number of) methods for the implementation.



来源:https://stackoverflow.com/questions/9392813/why-the-coding-should-be-to-the-interface-especially-for-primitive-datatypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!