A difference in style: IDictionary vs Dictionary
Solution 1:
If IDictionary is a "more generic" type than Dictionary then it makes sense to use the more generic type in declaring variables. That way you don't have to care as much about the implementing class assigned to the variable and you can change the type easily in the future without having to change a lot of following code. For example, in Java it's often considered better to do
List<Integer> intList=new LinkedList<Integer>();
than it is to do
LinkedList<Integer> intList=new LinkedList<Integer>();
That way I'm sure all following code treats the list as a List and not a LinkedList, making it easy in the future to switch out LinkedList for Vector or any other class which implements List. I'd say this is common to Java and good programming in general.
Solution 2:
This practice isn't just limited to Java.
It's often used in .NET as well when you want to de-couple the instance of the object from the class you're using. If you use the Interface rather than the Class, you can change the backing type whenever needed without breaking the rest of your code.
You'll also see this practice used heavily with dealing with IoC containers and instanciation using the Factory pattern.
Solution 3:
Your friend is following the very useful principle:
"Abstract yourself from implementation details"
Solution 4:
You should always attempt to program to the interface rather than the concrete class.
In Java or any other object oriented programming language.
In .NET world is common to use an I
to indicate that is an interface what your're using. I think this is more common because in C# they don't have implements
and extends
to refer class vs interface inheritance.
I think whey would type
class MyClass:ISome,Other,IMore
{
}
And you can tell ISome
an IMore
are interfaces while Other
is a class
In Java there is no need for such a thing
class MyClass extends Other implements Some, More {
}
The concept still applies, you should try to code to the interface.
Solution 5:
For local variables and private fields, which are already implementation details, it's better to use concrete types than interfaces for the declarations because the concrete classes offer a performance boost (direct dispatch is faster than virtual/interface dispatch). The JIT will also be able to more easily inline methods if you don't unnecessarily cast to interface types in the local implementation details. If an instance of a concrete type is returned from a method that returns an interface, the cast is automatic.