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?
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.
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.
Your friend is following the very useful principle:
"Abstract yourself from implementation details"
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.
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.
Most often, you see the interface type (IDictionary) used when the member is exposed to external code, whether that be outside the assembly or just outside the class. Typically, most developers use the concrete type internally to a class definition while they expose an encapsulated property using the interface type. In this way, they can leverage the concrete type's capabilities, but if they change the concrete type, the declaring class's interface doesn't need to change.
public class Widget
{
private Dictionary<string, string> map = new Dictionary<string, string>();
public IDictionary<string, string> Map
{
get { return map; }
}
}
later can become:
class SpecialMap<TKey, TValue> : IDictionary<TKey, TValue> { ... }
public class Widget
{
private SpecialMap<string, string> map = new SpecialMap<string, string>();
public IDictionary<string, string> Map
{
get { return map; }
}
}
without changing Widget's interface and having to change other code already using it.
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.
As far as I've seen Java developers tend to use abstraction (and design patterns) more often than .NET developers. This seems another example of it: why declare the concrete class when he'll essentially only be working with the interface members?
In the described situation almost every Java developer would use the interface to declare the variable. The way the Java collections are used is probably one of the best examples:
Map map = new HashMap();
List list = new ArrayList();
Guess it just accomplishes loose coupling in a lot of situations.
Java Collections include a multitude of implementations. Therefore, it's much easier for me to make use of
List<String> myList = new ArrayList<String>();
Then in the future when I realize I need "myList" to be thread safe to simply change this single line to
List<String> myList = new Vector<String>();
And change no other line of code. This includes getters/setters as well. If you look at the number of implementations of Map for example, you can imagine why this might be good practice. In other languages, where there is only a couple implementations for something (sorry, not a big .NET guy) but in Objective-C there is really only NSDictionary and NSMutableDictionary. So, it doesn't make as much sense.
Edit:
Failed to hit on one of my key points (just alluded to it with the getter/setters).
The above allows you to have:
public void setMyList(List<String> myList) {
this.myList = myList;
}
And the client using this call need not worry about the underlying implementation. Using whatever object that conforms to the List interface that they may have.
Coming from a Java world, I agree that the "program to an interface" mantra is drilled into you. By programming to an interface, not an implementation, you make your methods more extensible to future needs.
I've found that for local variables it generally doesn't much matter whether you use the interface or the concrete class.
Unlike class members or method signatures, there is very little refactoring effort if you decide to change types, nor is the variable visible outside its usage site. In fact, when you use var to declare locals, you are not getting the interface type but rather the class type (unless you explicitly cast to the interface).
However, when declaring methods, class members, or interfaces, I think that it will save you quite a bit of headache to use the interface type up front, rather than coupling the public API to a specific class type.
Using interfaces means that "dictionary" in the following code might be any implementation of IDictionary.
Dictionary1 dictionary = new Dictionary1();
dictionary.operation1(); // if operation1 is implemented only in Dictionary1() this will fail for every other implementation
It's best seen when you hide the construction of the object:
IDictionary dictionary = DictionaryFactory.getDictionary(...);
I've encountered the same situation with a Java developer. He instantiates collections AND objects to their interface in the same way.
For instance,
IAccount account = new Account();
Properties are always get/set as interfaces. This causes problems with serialization, which is explained very well here
Related
Note: I know this is an awful idea in practice; I'm just curious about what the CLR allow you to do, with the goal of creating some sort of 'modify a class after creating it' preprocessor.
Suppose I have the following class, which was defined in another assembly so I can't change it.
class Person {
public string Greet() => "Hello!";
}
I now define an interface, and a method, like the following:
interface IGreetable {
string Greet();
}
// ...
void PrintGreeting(IGreetable g) => Console.WriteLine(g.Greet());
The class Person does not explicity implement IGreetable, but it could do without any modification to its methods.
With that, is there any way whatsoever, using Reflection, the DLR or anything else, in which an instance of Person could be passed successfully to PrintGreeting without modifying any of the code above?
Try to use the library Impromptu-Interface
[The Impromptu-Interface] framework to allow you to wrap any object (static or dynamic) with a static interface even though it didn't inherit from it. It does this by emitting cached dynamic binding code inside a proxy.
This allows you to do something like this:
var person = new Person();
var greeter = person.ActLike<IGreetable>();
You could use a dynamic wrapper object to wire this up yourself, but you lose type safety inside the wrapping class:
class GreetableWrapper : IGreetable
{
private dynamic _wrapped;
public GreetableWrapper(dynamic wrapped)
{
_wrapped = wrapped;
}
public string Greet()
{
return _wrapped.Greet();
}
}
static void PrintGreeting(IGreetable g) => Console.WriteLine(g.Greet());
static void Main(string[] args)
{
PrintGreeting(new GreetableWrapper(new Person()));
Console.ReadLine();
}
This may be quite easy soon. Type classes may be introduced to C# as shapes where you will be able to define features of a class and code against that shape and then make use of your code with any type that matches without the author of that code having to declare anything, pretty much as you describe.
The closest thing in C# right now is perhaps how foreach works with a type that has an GetEnumerator() returning an object of a type with a MoveNext() and Current even they don't implement IEnumerable etc. only while that is a built-in concept the compiler deals with, here you could define them.
Interestingly, it will also let you define static members.
I don't believe this is possible. The compiler needs to see something that explicitly implements the interface or class so that the compiler can confirm everything is implemented.
If you could do it using redirection, you could fail to implement something. And that goes against the safety approach embraced by .NET.
An option is creating a wrapper class over the person and pass this wrapper to the method, the wrapper need to explicitly implement the interface.
If you have control of the external code, and are willing to wrap the object (and it seems like all of the answers here wrap), dynamic binding and libraries like Impromptu-Interface seem to me like a lot of trouble for something that's essentially a one liner.
class GreetablePerson : Person, IGreetable { }
And you're done.
When the compiler is building up the GreetablePerson class, the method from Person ends up doing an implicit implementation of the interface, and everything "just works." The only irritation is that the code outside has to instantiate GreetablePerson objects, but in standard object oriented terminology, an instance of GreetablePerson is an instance of Person, so this seems to me like a valid answer to the question as asked.
If the requirements are changed such that you also have pre-existing instances of Person, then something like Impromptu-Interface may become more tempting, but even then you may want to consider giving GreetablePerson a constructor that copies from Person. Choosing the best path forward from there requires getting more details about the requirements and the actual implementation details of the Person class in question.
In sort of an unrelated not, this is something that is commonly done in other languages, such as Scala and Haskell.
It's known as using what are called "type classes". Type classes essentially allow you to define behavior for a type as if it explicitly implemented an interface, without actually requiring it to do so. You can read more about it here.
I was advised to change a List<string> property to a Collection<string>, in a base class, because it is more appropriate for inheritance.
This 'rule' was referred to: https://msdn.microsoft.com/en-us/library/ms182142.aspx
System.Collections.Generic.List is a generic collection that is
designed for performance and not inheritance.
System.Collections.Generic.List does not contain virtual members
that make it easier to change the behavior of an inherited class. The
following generic collections are designed for inheritance and should
be exposed instead of System.Collections.Generic.List.
System.Collections.ObjectModel.Collection<T>
System.Collections.ObjectModel.ReadOnlyCollection<T>
System.Collections.ObjectModel.KeyedCollection<TKey, TItem>
Does a similar rule apply to Dictionary<string, string>?
I ask because it is also in the System.Collections.Generic namespace. Or maybe I have misunderstood and the rule only applies to Lists.
BTW, the Dictionary purpose is to hold errors (in a similar format to ModelState). I am not currently sure at exactly what stage I will be adding errors to it.
If I should be avoiding Dictionary<string, string> in the base class, what should I be using in it's place?
I have come across KeyedCollection but not sure if that is a good replacement.
Dictionary<TKey, TValue> does not have any base class you can use instead of it. It may be better to use interface (IDictionary<TKey, TValue> or maybe IReadOnlyDictionary<TKey, TValue> -both implemented by Dictionary), but it depends on your needs.
Note that it is very hard to express whether property returns internal storage or clone (and hence what happens when caller changes object) - you may want to consider IEnumerable<T> or methods that hide dictionary as implementation details.
So basically what you were told could potentially be wrong for the use case you are going for.
The statement in the msdn article means by inheritance if you want to create your own implementation of a collection by deriving from it like so:
public class MyCollection : Collection<MyType>
The advantage of using Collection<T> in this scenario is that you can alter the behavior significantly as it exposes the following methods which can be overriden: ClearItems, InsertItem, RemoveItem and SetItem. When you derive from List<T> you can't override any methods at all (except for the standard ToString, Equals and GetHashCode).
But as you stated in your comment you use the List/Dictionary/Collection as a property. Therefore it rather depends on your own use case.
If you want deriving classes to just use the collection from the base class you can let it be whatever you think is best suited for your needs. But if you think that the deriving class will know better which collection to use then you should
pick an interface from the System.Collections.Generic namespace.
I won't tell you which types or interfaces you should use when as it heavily depends on which functionality you need.
And by the way: the KeyedCollection can only be used to create your own key value collection (it is abstract). Therefore having a KeyedCollection as a property would mean that you'd also need an implementaion of a KeyedCollection.
I'm used to instantiate object as following:
type obj-name = new type();
and now I'm using
IList<string> str_element = new List<string>();
I was expecting to see something
IList<string> actors = new IList<string>();
can somebody give me some ideas why for interface instantiation is different here?
Thanks,
Amit
An interface is just that — an interface, or a specification of what methods should exist.
An interface does not contain any actual code.
Interfaces can only be used as types that hold concrete classes.
It doesn't make sense to create an instance of an interface, since there is nothing to instantiate.
The reason you can't do = new IList<string>() is because IList<T> is an interface and you can't initialize interfaces as there is no body of code to call. I would reccomend doing
List<string> actors = new List<string>()
instead.
Interfaces define a contract, or set of functionality, that implementing classes must provide (at a minimum). By defining a variable of type IList<T>, you are really saying, "I don't care what the actual implementation is, it just needs to provide that functionality." This means you are divorcing the 'interface' and the 'implementation' in your calling code, which is a good thing.
The real power of interfaces is where you have pluggable code. If you were defining a library, rather than returning a List<T> instance, you could return an IList<T> instance (which AFAIK, is what the LINQ functionality does). This allows you to change the internal implementation of the object returned (it might be a linked list, or a B-Tree, or whatever), and calling code doesn't need to change.
Alot of the mocking libraries out there (e.g. NMock, Moq, etc) take advantage of interfaces and can generate implementing classes for testing purposes.
You can use LINQ: for example
This will give you something of a more Concrete Type.
using System.Linq;
IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList()
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was.
But, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechanism to provide statically type checking.
So, dynamic ( OO ) programming languages do use interfaces, even thought they don't statically check them. Just like other data types, for instance in Ruby:
#i = 1;
You don't have to declare i of type FixNum you just use it. Same goes for interfaces, they just flow. The trade-off is, you can't have a static check on that and failures are only show at runtime.
In the other hand Structural type ( or static duck type as I call it :P ) used by languages as Go or Scala, gives the best of both worlds.
1. See Daniel Earwicker comment about CORBA interface keyword
We don't require them, but we do support them. Check out Zope Interfaces (which can be and are used outside of Zope).
It's worth noting that, contrary to what many people will say as a first response, interfaces can be used to do more than document "what methods a class supports". Grzenio touches on this with his wording on "implement the same behaviour". As a specific example of this, look at the Java interface Serializable. It doesn't implement any methods; rather it's used as a "marker" to indicate that the class can be serialized safely.
When considered this way, it could be reasonable to have a dynamic language that uses interfaces. That being said, something akin to annotations might be a more reasonable approach.
Interfaces are used in statically typed languages to describe that two otherwise independent objects "implement the same behaviour". In dynamically typed languages one implicitly assumes that when two objects have a method with the same name/params it does the same thing, so interfaces are of no use.
One key thing about at least some dynamic languages that makes explicit interfaces more than a little awkward is that dynamic languages can often respond to messages (err, “method calls”) that they don't know about beforehand, even doing things like creating methods on the fly. The only real way to know whether an object will respond to a message correctly is by sending it the message. That's OK, because dynamic languages consider it better to be able to support that sort of thing rather than static type checking; an object is considered to be usable in a particular protocol because it is “known” to be able to participate in that protocol (e.g., by virtue of being given by another message).
Interface constructs are used in statically typed languages to teach the type system which objects are substitutable for each other in a particular method-calling context. If two objects implement the same method but aren't related through inheritance from a common base class or implementation of a common interface, the type system will raise an error at compile time if you substitute one for the other.
Dynamic languages use "duck typing", which means the method is simply looked up at runtime and if it exists with the right signature, it's used; otherwise a runtime error results. If two objects both "quack like a duck" by implementing the same method, they are substitutable. Thus, there's no explicit need for the language to relate them via base class or interface.
That being said, interfaces as a concept are still very important in the dynamic world, but they're often just defined in documentation and not enforced by the language. Occasionally, I see programmers actually make a base class that sketches out the interface for this purpose as well; this helps formalize the documentation, and is of particular use if part of the interface can be implemented in terms of the rest of the interface.
Perl has Roles (or traits ), It is more than interfaces unlike java perl roles we can have a implementation check out these links for more on perl roles
http://en.wikipedia.org/wiki/Perl_6#Roles
http://use.perl.org/~Ovid/journal/38649
In C# and Java, interfaces are just abstract classes with all abstract methods. They exist to allow pseudo multiple-inheritance without actually supporting full-blown multiple inheritance and the ambiguity multiple inheritance creates.
Python supports multiple inheritance and has its own way of determining which parent's method should be called when a method exists in multiple parents.
Dynamic languages are Duck Typed
If it walks like a duck and quacks
like a duck, it must be a duck
http://en.wikipedia.org/wiki/Duck_typing
In other words, If you exect an object to suport the Delete() method, than you can just use the
obj.Delete()
method but if the object doesn't support Delete() you get a Runtime error. Statically typed languages wouldn't allow that and throw a compile time error. So you basically trade type safty against faster developement time and flexibility.
Without interfaces you can do something like that in static languages:
void Save(MyBaseClass item)
{
if (item.HasChanges)
item.Save()
}
but that would require every object that you pass to this method to inherit from MyBaseClass. Since Java or C# don't support muliinheritance that isn't very flexible because if your class already inherits another class it cannot inherit from MyBaseClass, too. So the better choise would be to create a ISavable interface and accept that as a input parameter to ensure that item can be saved. Then you have best of both: type safety and flexibility.
public interface ISavable
{
bool HasChanges {get;set;}
void Save();
}
void Save(ISavable item)
{
if (item.HasChanges)
item.Save()
}
The last backdoor is to use object as a parameter if you cannot expect every item that will use your save method to implement the interface.
void Save(object item)
{
if (item.HasChanges)
item.Save()
}
But than again, you don't have compile time checking and probably get a runtime error if someone uses your method with an incompatible class.
What is the need of IDictionary interface. How can IDictionary interface be initialized. After all it is just an interface. The following code snippet is from msdn. I could not understand it.
IDictionary<string, string> openWith = new Dictionary<string, string>();
It defines the important functions that an Dictionary should implement.
The line from MSDN means that you are creating an object openWith which implements the functions (methods) defined in IDictionary interface.
When you use Dictionary to declare the variable like:
Dictionary<string,string> openWith=.....;
you are bind with the concrete type of object. But when you use
IDictionary<string,string> openWith=....;
you can use it with any object that implements IDictionary interface, maybe your own custom class :)
The whole point of interfaces is to provide... well, an interface to whatever module (I use "module" in a broad sense here) so that calling code will not have to worry about how this particular interface is implemented.
As for "How can IDictionary interface be initialized", this is technically not correct. What can be initialized is a variable, whose type is IDictionary<T, V>. Sure enough variables have to be initialized, but that's usually hidden from the "client code".
IDictionary is not very representative, however. Rather, consider an IDataReader interface. You've surely dealt with ADO.NET, so this should look familiar:
public Foo PopulateFromDataReader(SqlDataReader dataReader)
This particular method is tightly coupled to an SqlDataReader, so you'd have to rewrite it for it to support, say, Access or Oracle or MySQL or Firebird or whatever. In other words, you depend on implementation.
Now consider:
public Foo PopulateFromDataReader(IDataReader dataReader)
This method can be used with whatever class that implements IDataReader, which means with basically any ADO.NET-compatible data provider.
It would be no different to any other interface. Try thinking about a simpler example:
interface IThermometer
{
double CurrentTemperature { get; }
}
Now we have a way to get the temperature, though we don't care exactly how it's measured. We can create various implementations:
class MercuryThermometer : IThermometer
{
public double CurrentTemperature
{
get { return ... /* gets the temperature somehow */ }
}
}
The rest of the program doesn't need to know which thermometer it's using.
I suspect you've simply overlooked the difference between the variable typed as IDictionary<,> (the interface), and the value (reference) initialized as a Dictionary<,> (note no I; the concrete type).
It's also useful for unit testing. You can write a unit test for a method that accepts an IDictionary instead of a Dictionary and pass a mock. If it were to accept a class instance (which could also be sealed) you'd be a little screwed (you'd have to use the adapter pattern and so on).