Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 409
user53885 Avatar asked Jan 14 '09 19:01

user53885


People also ask

When should a class have an interface?

In most cases, a final class is the best thing you can create. If a user doesn't like your class, they can simply choose not to use it. However, if you're building up a hierarchy of objects you should introduce an interface for every class.

Should I always create interfaces?

No, every class should not have an interface. It's overkill squared. You use an interface when you need to abstract what's done from how it's done, and you're certain that the implementation can change.

Why do we create interface?

Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling.

When would you use an interface example?

An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".


1 Answers

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.

like image 58
Jimmy Avatar answered Sep 25 '22 19:09

Jimmy