Inheritance design using Interface + abstract class. Good practice?

后端 未结 5 1662
时光说笑
时光说笑 2021-02-05 18:06

I\'m not really sure how to title this question but basically I have an interface like this:

public interface IFoo
{
    string ToCMD();
}

a co

5条回答
  •  故里飘歌
    2021-02-05 18:39

    The need for an inheritance chain is questionable, in general.

    However the specific scenario of combining an abstract base class with an interface.. I see it this way:

    If you have an abstract base class like this, you should also have a corresponding interface. If you have an interface, then use the abstract base class only where the inheritance chain is sensible.

    That said, if I'm writing a library and this is part of my API/Framework, I will generally include a "default implementation" that can be used as a base class. It will implement the interface methods in a naive, general way, where possible, and leave the rest for inheritors to implement/override as needed.

    This is just a convenience feature of the library though, to assist people who want to implement the interface by providing a functional example that may cover most of what they need to implement already.

    In short, the interface is more valuable than the base class, but a base class might save a lot of time and reduce buggy interface implementations.

提交回复
热议问题