What are Interfaces used for
I've seen a lot of people talk good things about Interfaces now and I see them used a ton
Personally I've not used them yet (in the sense of creating them), but what are the actual benefits from a perspective of someone who has used them in the past
20 Replies
Ah the interfaces. The question is a good one, but not that easy to understand, nor to explain correctly
Do you at least know what an interface is, before wondering what they are for?
Yes I have an idea
Afaik they allow for an easy implementation of stuff instead of creating objects or smth
Interfaces are what we could call "contratcs". When a class implements an interface it mean it must respect the contract (and so implements every method of the interface).
But then what's the benefit of them if I'm just gonna implement the functions over and over anyways
Being sure that something has a given behaviour
Have you ever used LINQ or foreach in C#?
it's like saying that every device has an usb port
the usb port project would be the interface
the device with the usb port would be the class, the implementation
you make sure that every device uses the same port, that it's always compatible
LINQ yes from time to time, foreach all the time
It's possible thanks to interfaces
Without knowing if you give it a List or an Array or whatever, it just needs to be sure it respect a given contract
The contact being IEnumerable
Would I also need to like implement all functions including the behavior and such
Yes you need to implement all methods of an Interface, the way you want
IEnumerals are lovely to use.
It just means that anywhere that needs that interface you can put whatever that respects it
Hm
The main goal is to decouple implementation from usage
For enumerables : I don't need to know how the data is stored or generated, just just want something I can iterate over
So if I were to have an interface of an entity for example
I'd create some Object (for example a player) and that player implements that Entity Interface to make sure the player has all of that Entity
For something like saving data : I don't need to know if it stores over network, in json or in database. I just need to know it saves my data and so has a Save() and Load() methods for example
Entity would likely make a poor interface
An interface is more about behaviours
A player could have an IWalkable IDrawable IControllable interfaces
Because, well, it can be drawn on screen, it can walk, and can be controlled
And the IControllable interface would make sure I implement all functions needed to move and such?
It would likely represent set of methods that makes it controllable by a human yeah
Hm
It's random ideas tho, not saying it's a good interface
IDrawable here is likely the best example