Why Interfaces?

ok I read lots of answers to this kind of question, mostly vs an abstract class…
but one stupid question stays in my head.
why would i use an interface!? and i don’t mean because it makes multiple inheritance possible or most other answers.
for example:
base class Mammal;
derived classes a bunch of mammals (cats, dogs, lions, hippo’s,…)
let’s say we make IPettable for cats and dogs and other domestic mammals and it has methodes like void LearnTrick()…

since adding an interfaces to my cat or dog class means i have to add all it’s methodes, events, properties,…
why not just add these as unique methodes for the class in question?
so Cat would have it’s unique method LearnTrick() as well as dog with totally different implementation… I don’t see the need to put this in an interface… more so i don’t see the point of interfaces existing :-s

which i guess is wrong since smart people invent these things :slight_smile:

An interface is a type, just like a class is. In the case of your IPettable interface, you could have a collection of these, and they will include any class that implements the interface, so you can treat them all the same way. For example you know they must all have certain methods in common (LearnTrick()) and you can call that method on any class that implements the interface.

Well you can add as many interfaces as you want to a class, and they become very useful when you need to be able to treat multiple objects in the same way, even if they are of different classes and the method to do so would be different.

There isn’t always a use for them but they can save a lot of time in places, though personally I find I use abstract classes and methods more often, or end up defining virtual methods.

If you ever had experience with a dynamic language like python, interfaces let you do something similar to “Duck Typing”.

1 Like

I’m halfway through Head First Design Patterns at the moment, and I can’t recommend it highly enough for an explanation of Object Oriented Design. Abstract classes and interfaces feature very strongly of course. It uses Java but that’s almost the same as C#. Not quite so close to Java(Unity)Script though.

@ christinanorwood ah ok maybe thats what I’m overlooking…
i could cast a bunch of “pet” classes into an interface and call .LearnTrick() on them all in an iteration… instead of one at a time through their class method…
something like that?
edit: thx I’ll check it out.
@ cmcpasserby same here i always end up building an abstract class or use some virtual methodes. Thats why i want to understand interfaces better, i feel like i’m missing out on something

You would need to use abstract classes if there was some data that all subclasses should have, or if some methods had an implementation in the base class. You would use an interface if you needed a bunch of different classes to have some method (named the same but implemented differently in each) and you wanted to use them interchangeably. You would also use an interface if there was no data involved, only methods.

1 Like

lets change you example a bit up.
so we have a class mammal and a bunch of derived types. Now lets say I want to be able to shoot mammal’s. I could implement a abstact/vitual method called “GetShot”, so far so good. Now I also want to be able to shoot red barels. But what have mammels and barels in common? not much if you ask me.
With intefaces you can create an interface like IShootable and let both mammal and red barrel implement the GetShoot method and if you shoot in your game you dont care if it is a mammal or a barel you can just reffer to them as IShootable

1 Like

yes but the thing is you still have to write the whole method in every class you want have GetShot() so that’s why i was asking why not just implement that method without interface… it would do the same and be less typing work.

but as christinanorwood convinced me it does come in handy if you think about polymorphism in a way that i could make a List of IShootables and they could be any type of class I can still collect them as a common group and iterate through them with GetShot() :slight_smile:

thats the only real advantage i see for now in using them.

1 Like

There is another advantage. If a class implements an interface it’s a guarantee that it has certain methods. Say an air traffic controller tells planes to land(), a method of the IFlyable interface. Then along comes a FlyingSaucer, a class that didn’t even exist when the airport was built. If it implements IFlyable then the controller knows it must have some implementation of a land() method, although there are no guarantees about what that method will actually do. At least it won’t throw an Exception if it is called.

2 Likes

Ok most of the responses here are either not quite on point or don’t explain the full story so I will try to correct and fill in the game.

An interface is exactly that, an interface for an object. It is not an object and cannot be instantiated.

The interface is valuable for breaking dependencies in code. In an example, let’s say you have a game where you are controlling something. That something could change mid game, like say, a boat, plane, car, or person. You could have an interface called something like IController, and give it a set of function signatures and events, such as moveUp, moveDown, moveLeft etc, anything that is common between all control schemes.

You would write your lasses like CarController, BoatController, etc. You could also easily release a patch later to add new control schemes, like space ship, and not need to rewrite the classes that call to the control schemes like your main application.

Now when you attach a class, it doesn’t matter what type it is, as long as it implements the iController interface. Otherwise, you would need to hardcode a reference to the carController etc, where this way, you can just use it like a plugin system.

A great way to think of it is it is like a plug and socket, like USB. It doesn’t matter what is plugged in, as much as it is important that it follows the standard protocol. This standard protocol is what is defined by the interface.

The core concept here is that it breaks inflexible dependencies.

For the best definition and use case, resort to MSDN. Although we are using unity, the core concepts of c# are easy to find references for at the MSDN site. I would HIGHLY recommend reading the following for anyone who hasn’t (even if they think they understand Interfaces). Read the whole thing and you will walk away well informed with interfaces :slight_smile: :

1 Like

C#'s limited class extensibility also limits the utility of interfaces. In Swift, you can add an extension to make any existing class conform to a protocol, which is its word for interface. Even when you’re working with your own classes/structs, it makes sense to put all of your protocol implementation into extensions. C# forces you to use subclasses, which can be painful when most of what you’re using is sealed, i.e. Unity.

1 Like

thx for the replies.
I get that it’s good for protocol but the plug and play concept confuses me because the actual implementation needs to be done in the class inheriting from the interface that only has a declaration…
It only makes sense to me looking at it from the polymorphism advantages but thats probably what you mean.
since my airport control script would look for a type it can cast into the right interface to get the land(); method…

Not so. As penguin said you can have animals or red barrels. There is nothing wrong with using both base classes and interfaces. In this case, animal would implement ishootable and cat, dog, etc. could inherit animal. Now GetShot only has to be created in animal and overridden if you want to change it.

Now you can also have a List and put any animal into it. You could also put all animals and all red barrels into the same list. So now lets say you have an explosion that needs to damage everything… If they are all IShootable then you can group them and call the method on everything. It’s not about making you do less work, its about decoupling, creating contractual code, and helping you write better code. Each has its place.

Another interesting tidbit… You can actually create an interface that doesn’t define any properties or methods. We call them marker interfaced as we primarily use them to mark classes for identification with dependency injection.

1 Like

I’d like to see an example of this; I don’t understand why an interface would be needed for this instead of an attribute.

Well one example is when we use the unit of work pattern. On large projects we have multiple repositories. We have a unit of work base class that handles wiring up all of the iqueryable stuff. But it’s in a core library and exposes the repository via an irepository interface. We need the di container to be able to inject with the correct repository so we use an iunitofwork where t : Irepository. The interface has nothing in it. But it allows us to mark each concrete unit of work so the proper db repository is injected at runtime. We are using interfaces and a bootstrap attribute along with Unity (the IOC framework not unity the game engine). The bootstrap automatically finds the assemblies and concrete classes that match the interfaces and wired them up. It’s 100% convention based so we don’t have to explicitly define any mappings.

1 Like

An attribute requires reflection to see if it’s applied to a specific instance. A marker interface would only require a cast attempt (if (b is IMarker) {…})
Also, as Dustin alludes to, if you’re doing generics-heavy coding, you can restrict generic params by class or interface.

2 Likes

starting to see the power of the interface! :slight_smile:

You also have to remember that an interface can define events. So even if you had no methods or properties, you could use it for events.

As for another use case, that will help you understand the plugin style system, look into what is called the factory model design pattern:

http://msdn.microsoft.com/en-us/library/cy5kfe3c(v=vs.110).aspx

I am using this now in a project for controls, because I don’t want to force one control scheme. I will also allow for developers to load in their own script, and as long as they implement the control interface, they can use their own code.

This means that the game has built in a biped, and flying ship control scheme. They all do the same things, meaning the function calls and responding to input, but the behavior is much different. A user could load in their own c# script, and my code will expect the interface, and jsut call “UpdateLookRotation(Vector3 MouseCoords)” etc, and if they want to have a control scheme for a car, boat or whatever, then it will ‘just work’.

It is really only painful if your design conflicts with standard programming models. Also it can be painful if you are not fluent in the language. Sometimes when you are new to a programming paradigm or language, you expect for things to work like what you are used to. One example, is that after working with KnockoutJS I found AngularJS to be quite painful, until I became proficient and now knockout feels painful. There is nothing really painful about c# once you become fluent with the language and its syntax.

I don’t mean to argue with your opinion about pain points, but it is important to note that it is in fact, just an opinion based on your background.

1 Like