Home c# Why came up with interfaces?

Why came up with interfaces?

Author

Date

Category

On the Internet, many articles on the subject of interfaces, what it is and how to implement them.
But I did not find a distinct answer who and why did they come up with?
I just start learning C # and I do not see the meaning in the interfaces at all. Classes are convenient for example in a situation when we need to create many enemies in the game, we do not need to prescribe parameters each enemy, you can set everything in the class.
Here is an example from methanin:

interface iMovable
{
  Void Move ();
}

Implementation in class:

// Applying an interface in class
Class Person: Imovable
{
  Public Void Move ()
  {
    Console.Writeline ("Man goes");
  }
}
// Application Interface in Structure
Struct Car: iMovable
{
  Public Void Move ()
  {
    Console.WriteLine ("Machine is driving");
  }
}

But if I just delete the interface and make it like this

class person
{
  Public Void Move ()
  {
    Console.Writeline ("Man goes");
  }
}

code will still work.
So why is it all necessary?
I just can’t imagine the situation where it would be necessary to use interfaces.
In C # 8, the default method was implemented in the interface thereby making an under-class interface.
I watch the video on YouTube and everything uses interfaces, but do not say why, just as if it is necessary.
Do not all use them all use? But without understanding why all this I need it simply does not work out to find the meaning of their application and understand how someone else’s code works when there are interfaces.
The only point in them see that you do not need to write documentation for classes, just inherit from the interface, and then let another programmer climbs into the code and watches what is there and how.
In no case, I do not want to say that I’m the smartest here and all the others were mistaken, I just want to figure out why came up with interfaces if it all worked well?
Sorry that I wrote so shatterously, myself on emotions, I already read articles on the topic and I can’t alter.


Answer 1, Authority 100%

There is at least 4 reasons for using interfaces. They can be more, but I write text from my head, because the remaining reasons, if there are such, thug or impair themselves.

Let’s start with how large and complex systems are built. The main mechanism of constructing something large is the separation of this large on small parts, determining how these parts interact, and then programming each of the parts.

The key point here is that you cannot immediately think over all these small pieces and write all the classes for them.

Let’s take a typical example. You write your game and you need to provide for saving your game. You know exactly what you need to save, but you still do not know where you will save to a file or in database or transfer data to the server. What to do in such a situation?

In this situation, the interface will help you. For example, you have a class that you need to save.

Public Class MyGameState
{
  // ... My Game Data
}

West for it Conservation Interface

public interface igmestore
{
  Void Savegame (MyGameState State);
  MyGameState Load ();
}

What happened here? There is no use in nature in nature, there is no code for him, what a class it will be, what the storage class will be the inheritance hierarian, nothing is known, but you have already identified how your game will interact with this, not yet existing class. You can write this class later, or it can write any other programmer and everything will work, since the contract of your future class is already known – you have already identified using the interface all the methods needed for a class.

In other words, the interface helps to determine the interaction between the modules of your program, even if these modules do not yet exist.

But here you can argue to me and say – that you can define a class to save with the same success, for example

Public Absract Class Gamestore
{
  Public Abstract Void Savegame (MyGameState State);
  Public Abstract MyGameState Load ();
}

Yes, it is true, you can define an abstract class. In this case, to implement the preservation, you will need to inherit from the abstracted class and implement the necessary methods. But let’s think about what restrictions does it impose on our preservation class? But what kind of saving class should be inherited from the specified abstract class and no more from anyone. You can argue – they say, in the case of an interface there will be the same – because the storage class must implement it. But here is not – in C #, the interface implementation does not limit the class, since the class can implement any interfaces. But inheritance from the abstract class is another thing, because you cannot hire from 2 classes. Hence the second reason for using Interfers – The use of Interfers allows us to bypass the limitations of multiple inheritance .

Okay, well, let’s say, we decided that we will keep our game, but to save our game, we must know the name of the current player – that is, it is nickname. This is the requirement of lecture to express, adding the designer to our abstract class, which accepts the name of the player, for example (the code may not be replicated, I write it almost on the phone, but the idea should be clear)

Public Absract Class Gamestore
{
  PROTECTED STRING PLAYERNAME {GET; PROTECTED SET;}
  Public GameStore (String Playername)
  {
    PlayerName = Playername;
  }
  Public Abstract Void Savegame (MyGameState State);
  Public Abstract MyGameState Load ();
}

Now look what happened. We not only force classes to save the game to inherit from our abstract class, but also impose certain flaps on them. Are these restrictions on the rest of the game interesting? I think no. In this case, why should the rest of the game know about these flaps? There is no reason for this. Thus, using the interface, you declare the desired behavior. Using class – you declave the items. That is, when you had an interface in the game, you declared that “it doesn’t matter what will be for the object, it does not matter how it will be written, but I need it to keep it And download the state of the game “- that is, it was important to you that the object can do , it does not matter how it does it. This is the essence of encapsulation. When you use a class, especially if the class contains any extraneous parts, you already show you that it is important to you not just that the can do , but also who the object is and Which object has the items of implementation .

And now let’s look at it from the point of view of the game. The game, in fact, is not interested in knowing how and where it will be saved. The game is not interesting to save details. The game is not even interesting to the fact – whether the preservation class already written is essential. All that the game is needed is to get an object that contains the necessary methods to the game. Everything. With this approach, the connection between the game and the real class of preservation lies only through the interface, which is a much weaker bond. The class itself can be written as you like, keep any facilities or sales details, these restrictions and parts can change and be rewritten any number of times and everything will work until the save class implements the interface. Thus, Communication of classes through the interface is a weaker communication than the links of classes through an abstract class or directly , where are the conclusions:

  1. If you want to keep your modules weakly related (and you should want), use the interfaces
  2. to communicate

  3. When using interfaces to communicate, the burden of interoperability falls on them – interfaces should be changed as little as possible
  4. Since interfaces should be changed as little as possible, writing an interface becomes more of a challenge than writing a class. A class closed by an interface can always be rewritten. The interface used in many components is not always possible to rewrite, and there is a high risk of losing backward compatibility with previously written code.

Answer 2, authority 30%

Classes express the underlying hierarchy and often define the internal behavior of descendants.

Interfaces express individual external behaviors and relatively small hierarchies. Or such features of behavior that are inherent in different class hierarchies and are important for some code, moreover, it does not care about the basic behavior.

For example, there may be a large hierarchy of living organisms – kingdoms, families, species from biology. These are all many different abstract and final classes. At the same time, additional hierarchies can be distinguished – for example, the ability to move (IMovable ), which can be inherited into the ability to walk (IWalking ), fly (IFlying ), swim (ISwimming ). Importantly, the same interfaces can be implemented by classes from a completely different hierarchy like technology – cars, tanks, airplanes, ships and boats.

Interfaces express something important to behavior, but not related to the underlying implementation. Yes, they can have their own methods, but this is again related to the specific topic of the interface, and these methods can only rely on methods of the interface by simply extending them.

For example, ISwimming can provide an abstract method void swim (float speed); and concrete methods like void swimSlowly () {self.swim (0.3); } .

The example is not realistic, but in reality everything is the same, only instead of all understandable animals and techniques, more often abstract data structures and clever manipulations with them. Among the most popular are serialization (ISerializable ), display with formatting, conversion to some formats, etc. And there may be large functions or even libraries that will accept objects of such interfaces for transmission over the network, saving to a file, or beautiful display. And they don’t care about the main behavior of a class, whether it’s a binary tree, a computation graph, a picture or a game character.


Why did you come up with interfaces if everything works well without them?

Of course, in one monolithic code base, you can implement everything in one class hierarchy, but in a large project with a bunch of functionality, these classes will turn out to be very overloaded. And industrial development is much more difficult, it has a lot of encapsulation, libraries and frameworks that are developed by different teams. And there without interfaces that allow you to link different levels of abstraction and the code of different commands without restriction in implementation, it would be difficult.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions