C #: from medium to advance level (Interfaces)
Here is another incredibly useful topic : Interfaces.
Start with syntax
Interfaces are ALWAYS public, we don’t have an access modifier, we declare them with keyword “interface” and the name is always starting with I and then the name : IWalkable, IAttackable, IDamagable, etc. This is for convention.
And they haven’t implementation, we declare only the body of method.
We use Interfaces because of their loosey-coupled.
Class coupling is one of the common problems when we work in large projects and with many classes and the interfaces help us a lot to solve this problem.
I use this simple example in practice.
We have a Player, it has three State (or more if you want, I use only three just for test it).
Every State has a method for describe it, i call it Print().
We use this method in every State thanks to an Interface.
This is a really basic example, just to understand how work Interfaces and Loose-coupling.
Now, I create three State, Walk, Jump and Run, and implement the Interface in every one of them.
Three Classes with IDebugState implemented.
We need the Player Class.
Inside it, I create one simple method and pass in the IDebugState inside it
When we use different Classes, we need an instance of that Classes to use them ok? If are static no, but normally we create an instance of that objects.
So, if I don’t use the interface, maybe I need something like this
I know, this is horrible code, but it is just to understand one simple point.
If we need an instance of Run, Walk and Jump, without interface we create Class coupling.
Because in this moment, inside Player Class we are directly dependat from Run, Walk and Jump.
Obviusly we need the reference of those object, but in the moment we pass the Class reference directly in the Player Class, we can have some problems.
If I use this system, the Main program can be something like that
And it works, even it is not a good code it works
Now, if I use the Execute method of Player
What is the real difference?
Let’s look at Main program
Ok, now we need to pass a IDebugState interface as parameter.
We can’t create an instance of Interface, it is like abstract Class, they can’t be instantiate.
But we can pass at runtime everything implement that Interface.
For example, Run()
In this way, in Player Class we have one single method, which take an Interface as parameter.
In any of our State we have different implementation of that method, and at runtime we call what we need.
Interface and Polymorphism are probably one of the most powerful thing in C# programming.
We can create a big project with so many Classes, but with this system, even if every Class have to “talk with other”, they are completely separated between them.
Again, I know this is a stupid example, in real world application / game the things can be (and they are probably) much more complicated, but if we understand the logic at base, everything becoming more comprehensible.