variable declaration: why interface
I've been doing some sax parsing in Java recently. I noticed the initialization for namespace mappings
private Map<String,String> namespaceMappings = new HashMap<String,String>();
my question is why we create开发者_StackOverflow a Map variable instead of HashMap here?
Further, if I'm going to have the getNamespaceMappings field, what type should I return?public Map<String,String> getNamespaceMappings() {
return namespaceMappings;
}
or
public HashMap<String,String> getNamespaceMappings() {
return (HashMap<String,String>) namespaceMappings;
}
or
public Map<String,String> getNamespaceMappings() {
return (HashMap<String,String>) namespaceMappings;
}
You should always declare variables and return types as the least specialized classes possible, or, ideally, as interfaces, so that you can at any time change the implementation.
For example, if at some point you decide you want to use a TreeMap
instead of a HashMap
, then you'd only need to change:
private Map<String,String> namespaceMappings = new HashMap<String,String>();
to:
private Map<String,String> namespaceMappings = new TreeMap<String,String>();
No other change needed in the code.
The most value you get out of this though is with what your class makes public. So for example, if you had the method getNamespaceMappings()
return a Map
, then every piece of code using that method will simply know that they will be using a Map
. If at some point you decide to internally represent this map as something other than a HashMap
, then you'll keep this internal to your class.
If you make the method return a HashMap
instead, then you're exposing implementation details. In the future, if you want to use something other than a HashMap
, then all the code using this class will need to be changed to accommodate this.
精彩评论