In ADO.NET, there are classes that inherit from abstract ones, and abstract classes, in turn, implement the interface.

For example, there are SqlCommand and OleDbCommand and mn that extend the abstract DbCommand , and DbCommand implements the IDbCommand interface.

In short, everything is inherited from the abstract DbCommand .

Why did Microsoft choose this implementation? In my opinion, it was possible to do without an interface.

Polymorphism could be achieved without using IDbCommand , but by IDbCommand classes to a base type.

  • The abstract class and interface have an important difference - a class can implement many interfaces. Without an interface, I cannot make my own implementation of a class that inherits some of my base class, because multiple inheritance is prohibited. So DbCommand is just a help in the implementation - vitidev
  • @vitidev, not. I mean: "If all concrete implementations are inherited from the abstract class DbCommand, then why do we need an interface? Why it was impossible to omit it in DbCommand? It seems that there are no other classes except DbCommand that implement it." - iluxa1810
  • one
    Because at the head of the design is exactly the interface. Only he allows me to create a hierarchy of MyDbCommand: MyDbCommandBase, IDbCommand. That is, the presence of the interface does not limit me in the implementation in any way (no multiple inheritance). The abstract class limits me in inheritance. So it is more correct to ask: "why do we need an abstract class, if there is an interface". - vitidev

1 answer 1

I understand the principles of design as follows:

If we need to describe only the contract - we choose the interface. So we can give the opportunity to apply this contract without restricting the programmer in its implementation (the interface does not impose restrictions on inheritance).

If we have some kind of mandatory code (for example, the "template method" pattern) and we want to impose its use, we choose an abstract class. Here the programmer will be forced to inherit from it.

If there are no requirements to "impose", then we describe the contract in the form of an interface and optionally we can generate abstract class (s) for the "boilerplate code"

With regard to DbCommand , there is a kind of implementation in the form of a heap of attached attributes on properties and so on, which is common to SqlCommand and in OleDbCommand , but the IDbCommand interface leaves freedom to those who do not need it.

In practice, it is unlikely that anyone will use IDbCommand , but for describing a contract, the interface is preferable, so we have an interface (as a contract description) and an abstract class (as a base class that allows you to optionally use common functionality).

ps: these principles for public code. In its own code, interfaces (abstract classes) should be born only when needed.