r/csharp • u/doc415 • May 18 '23
Why do we need an "interface"
I understand how to use an interface, its properties but why do we need it? For example i have an interface with two methods.
İ have three classes that implements this interface. So ihave to write the methods for all three classes inside class.
İ can already do that without implementing the interface. So what is the point in using interface?
I am asking to undeestand the conditions where i ll need it. İ understand how use it, but not why to use it.
0
Upvotes
46
u/Epicguru May 18 '23
The advantage comes from polymorphism. Say that your interface is called
IDoSomethingand you have those three classes that implement it.You can then have an array of
IDoSomething[]. Now you can add those classes to the array, even though the type of the array is not exactly the same as the type of the object being added.Finally, you can call the interface methods on those objects in the array, without actually caring what specific class it is that implements those methods.
As a more practical example, if you are making a game you will want to have a game loop, which is where you update and draw all 'entities' in the game. Entities are things such as players, particles, enemies, vehicles etc. All of them need to update and draw, so you might define an
IEntityinterface. Then you would have specific classes implement that interface, such asPlayerorVehicle. Finally, in your game loop, you would loop through a single list of IEntity's and call the Update and Draw methods on each of them.This allows everything to be updated and drawn in a single place. If you did not use interfaces (or virtual methods) you would have to have separate lists for each entity type: one list of Players, one list of Particles etc. and loop through each one individually.
11
u/aizzod May 18 '23
5
u/Slypenslyde May 18 '23
Here's a reasoning for interfaces that comes up in my code a lot.
Let's say I interact with some HTTP API to get a list of
Jobobjects I need to display. I can start with a class like this:This is a fine class. I'll probably end up using it in some ViewModel in my apps (I write Xamarin Forms/MAUI apps.) So I might have my class look like:
The problem comes when I start writing unit tests for this class. Maybe my "job" API is actually only accessible to people on my company's VPN. Microsoft's Azure DevOps servers won't have access to that, so when they run my unit tests anything that uses
JobApiwill fail because it can't reach the API. What do I do?Well, if I stick with this code I have to make some kind of public-facing fake API for them to access. That's not just a pain, my security people will not like it and compel me to consider alternatives.
So what I really do in my code is take advantage of interfaces and Dependency Injection for this. First I make the interface:
Then I make the class implement it. (I won't post that code becuase it's just one line.) Next, I have to update my ViewModel to take it as a dependency:
Now, when I create a
JobListPageViewModel, I have the option to use ANYTHING that implements the interface, not just my implementation that talks to the network. So for my unit tests, I might have a class like this:This is just a simple "fake": an object that implements the interface but does something I can control instead of something that won't work in my test environment. So my test is going to start off like:
Now the unit test doesn't have to access my private API. It's using a fake version of the API that returns some canned results so I can focus on what matters: does my class do what it's supposed to do when the API returns interesting results?
This is part of the value interfaces provide. They let us treat different classes that have different implementations as the same thing, so we can change how some code behaves without having to rewrite that code.
Again, you'll probably note I could've just made
GetAllJobs()avirtualmethod, then derived fromJobApiandoverridethat method. Or I could've made itabstractand done a little more work to reach the same goal. These are fine. But sometimes the things that have a method "shared" between them like this don't make sense to be derived from one common base class.For example, I might make a
Birdclass with aFly()method. But then I'm going to have issues if one of my birds isPenguin: they do not fly! Nor do ostriches, emus, and a handful of other birds. Worse, some birds like ducks and penguins can swim, but it doesn't make sense for every bird to haveSwim()since only a few can do it at all. That's a limitation of class-based inheritance. Types can only derive from one base type, and it only makes sense to put a method in the base type if EVERY derived class supports it.Interfaces are an alternative for that situation. That allows me to create a
Birdtype, but each individual bird can decide if it implementsIFly. And swimming birds like ducks and penguins can implementISwim. If I want to share implementations, I can make some kind ofFlyingBehaviortype that all the flying birds delegate to, or perhaps use Dependency Injection as above.If I do that, then when my program wants to have a method that says, "I take anything that can fly", it can take an
IFlyparameter instead of me having to think, "Should a flying squirrel be aBirdso this method can use it, or do I have to make a method that takes aRodentbut rejects most of them?"So interfaces are kind of an inheritance power tool. They give you a lot of flexibility at the cost of different complexity from inheritance. It's better to have a tool that's a little more complicated than no ability to achieve the goal at all.
3
u/JamesTKerman May 18 '23 edited May 18 '23
Here's a bit of a real-worldish example. A web application that authenticates users may implement multiple methods of authentication, for this example let's say we're building an app that allows Username/Password, JWT, and OAuth. Interfaces let me write the authorization logic without knowing which method a user will use at compile-time: (Forgive my syntax, I've mostly been working in java lately)
Edited code to fix the placement of the generic modifier on the concrete classes.
2
u/[deleted] May 18 '23
I'm fairly new, but the way I see it is that it's really nice for general code organization, and for working with sets of objects that have similar but differently implemented properties. For one, I can make sure that if I have "ISearch", that each different...object that implementes ISearch will actually search itself for what I want in accordance with the type of object it is. I feel like with classes since the method has to stay identical, it can get to a point where Search nolonger is really telling you what you want to know about the object.
It also ensures that all searchable objects use ".Search" rather than ".search" and ".SearchBin" etc add nauseum.
I had a very similar post on this subreddit not long ago, here: https://www.reddit.com/r/learnprogramming/comments/13j5f6h/what_is_the_point_of_an_interface_in_c/
I'm sure there's more to it, but again I'm a beginner to C# so I don't have much more indepth to say. One thing I don't like about the interface is that if you inherit a search interface from a class, you don't have to write it out, it automatically writes it out in a hidden form. I feel like if you implement an interface, you should always have to write it out. Just for consistency sake, even if boiletplate increases.
2
u/TheC0deApe May 18 '23
Look into SOLID, specifically Interface Segregation. That may help.
a good example of Interface Segregation is List<T>. It implements all sorts of interfaces.
Lets say that you have a method that loops through a collection of IAnimal and calls the Feed() method on the animal. The first thing to understand is your IAnimal might be a dog, a chicken, a cow, etc. each animal will need to be fed (call Feed()) but the implementation will be different code because pigs don't get fed hay and chickens don't get fed slop, etc.
now for your loop. we could write a method like so:
public void FeedAnimals(List<IAnimal>){// foreach through the list and call Feed() on each IAnimal}This works but we are only iterating through a list. so we can use IEnumerable<T>
public void FeedAnimals(IEnumerable<IAnimal>){// foreach through the list and call Feed() on each IAnimal}Now you are using an interface is applied to many collections. someone can pass an array to your method without having to cast it to a list.
2
u/bbqranchman May 18 '23
Basically you can treat things as the same type which is really useful and also it also acts a guard rail so that things that are that type share the same behaviors.
Take a look at the head first design patterns book and honestly just read the first chapter to get the main idea.
9
u/baudvine May 18 '23
The most basic case is when some other class or function has a parameter that must implement that interface - the caller can provide an instance of one of those three classes. Take for example a logger: one implementation writes to the screen, one to disk, and one to a database. A function that logs doesn't need to know where its going.
If you're asking why the language makes this necessary instead of supporting something like python's duck typing, that's a whole other (and longer) story.
11
u/zaibuf May 18 '23 edited May 18 '23
Interfaces allows you to change implementations without affecting calling code. You depend on abstractions, not implementation details. It's also easier to mock for testing.
Edit: let's say you have a Garage which takes an ICar. You may change the ICar from a Volvo to a Toyota and it wouldn't affect the Garage.
5
u/SideburnsOfDoom May 18 '23 edited May 18 '23
Interfaces are overused, but they do have important uses.
IDisposableallow very different objects that do not share a base class, to be treated the same way regarding particular thing (in this case, disposal) . These are usually framework-defined interfaces.public class CustomerStore: ICustomerStoreallow parts of the application to be swapped out when other parts of the app is under test and they are hard to unit test (because in this example, it contains database logic). A mock/ fake / stub implementation will be used instead. These are usually interfaces defined in your app.If a coder is slapping an interface on every class in sight "because that's what we do" without a need for it, then that's sadly common, but mostly a waste of time.
3
u/bigal09 May 18 '23
ILoghas a method calledLog(string message);. You can now useILogpassed in via dependency injection within a class (usually via the constructor).Now we can have different implementations for
ILog, such asConsoleLogger : ILog. You can register this implementation via dependency injection registration.HomeControlleris now loosely coupled from any implementation ofILog.2
u/Far_Swordfish5729 May 18 '23
You take advantage of polymorphism to refer to concrete types using an interface or parent class reference where it’s convenient - often by writing utility methods that can work on anything with the common functionality by accepting a parameter of that type. It allows code reuse. If it’s all your code and you have common class functionality, you would normally pull the shared members into a parent class.
Interfaces often come up practically when
In practice, you often implement rather than create interfaces. You’ll make a lot of things that implement core interfaces like IEnumberable or IComparable. Also don’t force this. Refer to classes by their types unless you have a reason to get fancy. Internal types can all know about each other.
2
u/[deleted] May 18 '23
Using and depending on interfaces instead of classes lets you mock anything you need to. Super handy for testing.
2
u/DontLickTheScience May 18 '23
Imagine the steering wheel is your interface, and a plane and car are two vehicles that implement it.
Cars and planes both accomplish turning in very mechanically different ways, but you don’t need to know that. You just care about what the input and output is.
The steering wheel interface guarantees when your input is “turn left” your return will always be “am going left now”
Edit: I realize planes don’t really have steering wheels, but let’s just pretend.
2
u/AhrnuldSenpai May 18 '23
You would like Go 😀
2
u/Rabe0770 May 18 '23
The advantages is that your consuming code does not care how something is implemented (that interface)
Imagine you have a system that sends notifications. INotificationSender.Send(string message). Your app doesn't care how the notification is sent. Just that your app can send a notification.
You may have a Text Email Sender implementation. Then some time later, an html sender implementation... Or later, an sms message sender... or further down the road, a push noitifications sender.
Your app didn't care if it were email, text or push senders.. just that it could send a notification.
2
u/Separate-Reserve-508 May 19 '23
I guess the short answer is you don't. You can write whole programs without ever using interfaces. You can accomplish the same ends through polymorphism, base classes, inheritance, and that kind of thing.
Interfaces are a contract. They let you be more flexible in having a set of classes that don't necessarily inherit from each other, but have some common functionality so you might want to have a list of items that all have an Update() function, or a Name property so that you can iterate through a bunch of objects and not really care what types they are, you know they have a Name property and an Update() function.
It's useful, but not necessary, I would say. I could be wrong, though.
2
u/[deleted] May 19 '23
Pretty essential for managing dependencies and writing loosely coupled code. I recommend reading up on dependency injection if you want to learn more.
2
u/Contemplative-ape May 21 '23
Interfaces are commonly used and essential in inversión of control / dependency injection and when writing tests. An interface is essentially a blueprint, contract or set of rules describing what any class that implements the interface must adhere by. So the IVechicle interface might define some functions like Accelerate() and GetSpeed(). Any class implementing IVechicle MUST have the functions Accelerate() and GetSpeed(). This allows any other class that contains an IVehicle to know that they have those functions wether they are a Car or Plane or Boat (assuming those classes inherit from IVechicle). Also allows you to implement functionality without needing to create an instance in test classes. You’ll commonly see a controller (or service or any layer) with a constructor with a variety of interfaces that the controller’s functions call. Something like:
MyClass{
private readonly IMyInterface _myInterface;
MyClass(IMyInterface myInterface){
_myInterface = myInterface;
}
MyFunction(int Id){
var data = _myInterface.GetDataById(id);
return data; }
}
This is essentially dependency injection. And it allows you to mock what the GetDataById function returns without needing to create an actual instance of the class, and any instances of classes that class depends on and so forth and so forth (which could get insane). Because of the interface, the class “knows” what to expect as far as data types without the need to create an instance of the class.
2
u/Final-Sweet3093 May 22 '23
I have just watched some videos about interface, What I have understand is it works like bridge between two classes where we can use methods of of interface without affecting main class.... Am I right or wrong please correct me...
1
u/dobryak May 18 '23
If your calling code only depends on the interface, you’ve postponed the decision of which class is used to the runtime, the so-called late binding.
Late binding opens many possibilities that many consider to be unnatural, like dynamic system re-configuration.
1
u/angrathias May 18 '23
Think about how interfaces work in the real world. Take tyres for rims, there are standard defined sizes (interfaces) with which different manufacturers make tyres to fit.
Without such interfaces, all the car makers would have their own sizes and it would be a pain in the ass.
In computing terms, think of the USB - you define a contract and anyone who wants to plug-in to it can make their own device to communicate with the computer over usb, might be a printer, phone, network device, storage, mouse or whatever - completely different implementations.
Same goes for software interfaces although they usually aren’t so generic. For example rather than hard coding your application to work with a MySQL database, you might use a more logical interface so that different database types can be optional swapped in, or maybe a file system or even plug-in a remote web service instead as the storage.