A difference in style: IDictionary vs Dictionary

Viewed 74263

I have a friend who's just getting into .NET development after developing in Java for ages and, after looking at some of his code I notice that he's doing the following quite often:

IDictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();

He's declaring dictionary as the Interface rather than the Class. Typically I would do the following:

Dictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();

I'd only use the IDictionary interface when it's needed (say, for example to pass the dictionary to a method that accepts an IDictionary interface).

My question is: are there any merits to his way of doing things? Is this a common practice in Java?

14 Answers

IDictionary is an interface and Dictionary is a class.

Dictionary implements IDictionary.

That means that this is possible to refer to Dictionary instance with/by IDictionary instance and invoke most of the Dictionary methods and properties through IDictionary instance.

This is very recommended to use interfaces as many as possible, because interfaces abstracts the modules and assemblies of the applications, allows polymorphism, which is both very common and useful in many situations and cases and allows replacing one module by another without touching the other modules.

Suppose that in the present, the programmer wrote:

IDictionary<string> dictionary = new Dictionary<string>();

And now dictionary invokes the methods and properties of Dictionary<string>.

In the future the databases has been grown up in size and we find out that Dictionary<string> is too slow, so we want to replace Dictionary<string> by RedBlackTree<string>, which is faster.

So all what is needed to be done is replacing the above instruction to:

IDictionary<string> dictionary = new RedBlackTree<string>();

Of course that if RedBlackTree implements IDictionary then all the code of the application compiles successfully and you have a newer version of your application, where the application now performs faster and more efficient than the previous version.

Without interfaces, this replacement would be more difficult to do and would require the programmers and developers to change more code that is potential to bugs.

Related