How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.
I frequently read about them but it just seems like I cannot grasp them.
I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"
What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.
Solution 1:
it solves this concrete problem:
you have a, b, c, d of 4 different types. all over your code you have something like:
a.Process();
b.Process();
c.Process();
d.Process();
why not have them implement IProcessable, and then do
List<IProcessable> list;
foreach(IProcessable p in list)
p.Process();
this will scale much better when you add, say, 50 types of classes that all do the same thing.
Another concrete problem:
Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.
Solution 2:
I like Jimmy's answer a lot, but I feel I need to add something to it. The key to the whole thing is the "able" in IProcessable . It indicates a capability (or property, but meaning "intrinsic quality", not in the sense of C# properties) of the object that implements the interface. IAnimal is probably not a good example for an interface, but IWalkable might be a good interface to have if your system has many things that can walk. You might have classes derived from Animal such as Dog, Cow, Fish, Snake. The first two would probably implement IWalkable, the latter two don't walk, so they wouldn't. Now you ask "why not just have another superclass, WalkingAnimal, that Dog and Cow derive from?". The answer is when you have something completely outside the inheritance tree that also can walk, such as a robot. Robot would implement IWalkable, but probably wouldn't derive from Animal. If you want a list of things that can walk, you type it as IWalkable and you can put all walking animals plus robots in the list.
Now replace IWalkable with something more software-y like IPersistable, and the analogy becomes much closer to what you'd see in a real program.