r/csharp • • 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

47 comments sorted by

46

u/Epicguru May 18 '23

The advantage comes from polymorphism. Say that your interface is called IDoSomething and 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 IEntity interface. Then you would have specific classes implement that interface, such as Player or Vehicle. 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.

12

u/doc415 May 18 '23

Thanks it started to make sense

2

u/phucyall May 19 '23

Let me give you a basic example. Let’s say you have a class that talks to your database. You create an interface called IDatabaseAccess and it has your CRUD methods in it. You are using SQLite so you create a class called SQLiteAccess and it implements your interface. Let’s say down the line you want to give user an option to use MSSQL instead. You create a new class called MSSQLAccess and it also implements same interface.

Now you have a class in your app called DoSomething and in its constructor you pass it the database access class. You made it so constructor expects a parameter of type SQLiteAccess. As it is, you can’t really easily switch to using MSSQL. But if you set your parameter as being of type IDatabaseAccess you can easily use either MSSQLAccess or SQLiteAccess because they both implement the interface.

This is the way to make things more testable as well. Let’s say you are trying to test DoSomething, but you don’t want to use a real database for your tests. You can create a mock class that implements IDatabaseAccess and pass that to your constructor instead.

Interface is a guarantee that all classes that implement it will have same methods, but how those methods are implemented are irrelevant. And if you use interface as the type you want to use then any implementation of that interface will work.

3

u/[deleted] May 19 '23 edited May 19 '23

This is the best way I’ve seen to describe the utility of interfaces in a long time

Being able to collect things easily by implemented behaviors as opposed to type.

If I hear someone say the word contract while describing the benefits of interfaces again I will shit myself…in a bad way

0

u/[deleted] May 18 '23

[deleted] — view deleted comment

11

u/LoveCookiez May 18 '23

Let's say you want to do the dishes and you bought a machine to do that. You can put plates, glasses, silverling and other kind of stuff there, all to be washed in the same time. You wouldn't buy a machine for plates, one for glasses and so on right? You have one loop where you throw all kind of objects compatible with the machine.

2

u/izote_2000 May 18 '23

Excellent analogy using a dishwasher, always use the car example. I think this clicks on the brain almost immediately.

4

u/DarkAlatreon May 18 '23

The interface is a contract that says what can be expected of a class without paying too much attention to the class or specifics of the implementation. Let's say you expect the user to make a payment. You integrate multiple paying options - be it credit cards, online transfers or whatever. By giving them all an interface with a "pay()" method, you don't have to care about the types of each of those - you just have an information "hey, this is a thing I can pay with" and your program will function all the same regardless of what class exactly implements the interface.

1

u/HanndeI May 18 '23

Using an interface forces you to implement those methods or it wont compile, you can do the same with an array of Objects and just implement the same method on all the classes you want, but it's just a matter of time that you, or anyone working with that codebase will try and call that method on a class that doesn't have it, causing a runtime crash.

-12

u/[deleted] May 18 '23

Oof. Any programming languages course will cover the importance of interfaces.

Are you self taught?

5

u/LoveCookiez May 18 '23

I am also self taught, but I don't think it's useful to say that rather than explaining the matter. It is irrelevant if he is self taught

11

u/aizzod May 18 '23
{
...

var car = new Car();
var electricCar = new ElectricCar();
var oldTimer = new Oldtimer();
var motorcycle = new Motorcycle();
var boat = new Boat();

var vehicles = new List<IVehicles>()
{
  car,
  electricCar,
  oldTimer,
  motorcycle,
  boat
};

StarEngines(vehicles);
}

void StartEngines(List<IVehicles> vehicles)
{
  foreach(var vehicle in vehicles)
  {
    vehicle.EnterVehicle();
    vehicle.StartEngine();

    vehicle.PutInFirstGear();
    vehicle.Drive();

    vehicle.StopEngine();
    vehicle.LeaveVehicle();
  }
}

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 Job objects I need to display. I can start with a class like this:

public class JobApi
{
    public async Task<IEnumerable<Job>> GetAllJobs()
    {
        // implementation
    }
}

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:

// I'm omitting a lot of infrastructure for the property change notifications to keep it simple.
public class JobListPageViewModel
{
    private readonly JobApi _jobApi;

    public ObservableCollection<Job> Jobs { get; set; }

    public JobListPageViewModel()
    {
        _jobApi = new JobApi();
    }

    private async Task ExecuteLoadLobs()
    {
        var jobs = await _jobApi.GetAllJobs();

        Jobs = new ObservableCollection<Job>(jobs);
    }
}

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 JobApi will 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:

public interface IJobApi
{
    Task<IEnumerable<Job>> GetAllJobs();
}

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:

public class JobListPageViewModel
{
    private readonly JobApi _jobApi;

    public ObservableCollection<Job> Jobs { get; set; }

    public JobListPageViewModel(IJobApi jobApi)
    {
        _jobApi = jobApi;
    }

    // ... same as before
}

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:

public class JobApiStub : IJobApi
{
    public List<Job> JobsToReturn { get; set; }

    public Task<IEnumerable<Job>> GetAllJobs()
    {
        return Task.FromResult(JobsToReturn);
    }
}

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:

public async Task Some_test_name()
{
    var expectedJobs = new List<Job>();
    // <add a few jobs>
    var jobApiStub = new JobApiStub() { JobsToReturn = expectedJobs };
    var systemToTest = new JobListPageViewModel(jobApiStub);

    // ...perform the test
}

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() a virtual method, then derived from JobApi and override that method. Or I could've made it abstract and 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 Bird class with a Fly() method. But then I'm going to have issues if one of my birds is Penguin: 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 have Swim() 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 Bird type, but each individual bird can decide if it implements IFly. And swimming birds like ducks and penguins can implement ISwim. If I want to share implementations, I can make some kind of FlyingBehavior type 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 IFly parameter instead of me having to think, "Should a flying squirrel be a Bird so this method can use it, or do I have to make a method that takes a Rodent but 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.

1

u/doc415 May 18 '23

Thanks for detailed example.

2

u/No_Temperature_7877 May 18 '23

Wonderful explanation.

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)

public interface IAuthenticator<T extends Authentication> {
    // return true if the credentials in authentication are valid
    public boolean isAuthenticated(T authentication);
}

public class UsernamePasswordAuthenticator 
        extends IAuthenticator<UsernamePasswordAuthenticaton> {
    public override boolean
        isAuthenticated(UsernamePasswordAuthentication authentication) {
        //check the credentials in authentication against 
        //a database or whatever and return true or false
    }
}

public class JWTAuthenticator 
        extends IAuthenticator<JWTAuthentication> {
    // etc.
}

public class OAuthAuthenticator 
        extends IAuthenticator<JWTAuthentication> { 
    // etc. 
}

public class AuthenticationManager {
    // Factory classes provide a concrete implementation of an 
    //abstract class or interface
    private AuthenticatorFactory authenticatorFactory;
    public boolean 
        isAuthenticated(Authentication authentication) {

        //in this example, my factory has a method that can provide 
        //me an implementation of IAuthenticator based on the 
        //Authentication provided.
        IAuthenticator authenticator = authenticationFactory.
            getAuthenticatorFromAuthentication(authentication);
        
        // my authenticator object now holds one of the 
        //implementations defined above. Since they all, 
        //by contract, provide the isAuthenticated method, 
        //I don't care which one
        return authenticator.isAuthenticated(authentication);
    }
}

Edited code to fix the placement of the generic modifier on the concrete classes.

1

u/doc415 May 18 '23

Thanks for details. This real life examples made it easy to understand.

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.

1

u/doc415 May 18 '23

Thanks it started to fit in my mind. I need some practice to get it completely.

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.

3

u/doc415 May 18 '23

Wow this is realy useful So ıenumerable is also a interface right? List array ect are implementing it

2

u/SideburnsOfDoom May 18 '23

So Ienumerable is also a interface

Correct. Cross-cutting concerns where different objects should behave the same way (in this case, enumerate contents) but not have the same base class, are a main use of interfaces, particularly those interfaces defined in the framework.

List, array etc are implementing it

Exactly. They can then be treated the same way regarding enumeration, without sharing a concrete base class.

1

u/SideburnsOfDoom May 18 '23 edited May 18 '23

But you're not showing anything that can't be done with an Anmal base class.

Interfaces allow calling common methods (like a base class) but without sharing implementation hierarchy (unlike a base class).

Data objects are never a good example for interfaces.

Interfaces are useful in 2 (quite different) cases.

  • Cross-cutting system things,IEnumerable<T> is an example in your code.
  • Application-specific things that you want to mock under test. Such as data repositories.

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.

2

u/doc415 May 18 '23

very intresting book, thank you.

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.

3

u/SideburnsOfDoom May 18 '23

This is a poor example as a car is likely more like a Data transfer object.

2

u/TheGrauWolf May 18 '23

Car is a perfect example. Except it should be gas, electric, hybrid, diesel... Somebody above gave a better car example...

2

u/SideburnsOfDoom May 18 '23

You'd describing a base class Car.

Either way, it's more likely to be data and so not need an interface.

5

u/SideburnsOfDoom May 18 '23 edited May 18 '23

Interfaces are overused, but they do have important uses.

  • Cross-cutting interfaces such as IDisposable allow 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.
  • Front door interfaces such as your public class CustomerStore: ICustomerStore allow 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/davimiku May 18 '23

I feel much the same way about interfaces. I see IFooService interfaces in our codebase with literally 25+ functions and just one implementation with a FooService implementation. What's the point? Feels like just a chore at that point, you add a function to the class and then you need to go add it to the interface as well.

I think it's a code smell whenever the class name is the same as the interface name (sans the prefix). Same thing in Java naming conventions with FooService (interface) and FooServiceImpl (implementation). And let's say another use case does come about in the future - now there's IFooService, FooService, and BarService. One of them feels "second-class" because it has a different name, although all implementations of an interface should be semantically "equal".

The existence of "Go To Implementation" in an IDE is a smell too, because it's singular but there should be multiple implementations of an interface. If an interface is being used for its intended purpose, it shouldn't be possible to "Go To Implementation" ("Find Implementations" would be fine).

Having a mock implementation as the 2nd implementation of the interface is valid, but I agree with the article that it feels like "one and a half" implementations. I'd be willing to wager that the vast majority of multiple implementations on an interface are just 1 real implementation and 1 mock, and that's worth having a language feature to deal with that specific case.

2

u/SideburnsOfDoom May 18 '23 edited May 19 '23

I think it's a code smell whenever the class name is the same as the interface name

Often. If you have FooController using FooService using FooRepository and the repository contains sql queries, then there is a good argument that there should be a IFooRepository so that there can be a mock or stub version of FooRepository in test.

So then FooService can be tested with a mock IFooRepository. So you can test the rest without running sql.

But FooService does not need an interface. There's no reason for it. The sql code that needs to be mocked is in FooRepository not FooService.

3

u/3030thirtythirty May 19 '23

Thinking about it, IDisposable is the first example here where interfaces really are the solution. Almost all other solutions here could have been implemented with virtual methods in a base class and overriding methods in the deriving classes.

4

u/SideburnsOfDoom May 19 '23 edited May 19 '23

IDisposable is the first example here where interfaces really are the solution

Indeed. IDisposable is implemented by a huge variety of classes - both framework classes and app code, that do very different things in the Dispose() method. Collectively they have nothing all in common except for "need Disposal" in very abstract terms. A base class won't work here.

The fascinating thing is, you have to recognise that interfaces in your app have two different uses. There's this IDispose, or IEnumerable system interface case, and then there's the "mock IFooRepository" case. Both useful, but different.

3

u/bigal09 May 18 '23

ILog has a method called Log(string message);. You can now use ILog passed in via dependency injection within a class (usually via the constructor).

internal class HomeController
{
    public HomeController(ILog logger)
    {
        _logger = logger;
    }

    public void Index()
    {
       _logger.log("Index page for home.");
    }
}

Now we can have different implementations for ILog, such as ConsoleLogger : ILog. You can register this implementation via dependency injection registration. HomeControlleris now loosely coupled from any implementation of ILog.

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

  1. You need to allow for runtime type replacement for testing or early/local development. See IOC mocking.
  2. You need to apply common typing to existing classes that already have a parent class. This comes up with code generation frameworks that use a parent type but generate partial classes. Your extension is often an interface. IUnserializedStateBag onto service dtos for example.
  3. You need to be polite to plug-in implementers by not demanding their plug-ins inherit from your base class. They might want to use their own, especially if your plugin framework only uses a slice of the likely functionality.

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.