Interface / Abstract Class Coding Standard

后端 未结 5 851
礼貌的吻别
礼貌的吻别 2021-02-09 06:01

I spotted a proposed C# coding-standard which stated \"Try to offer an interface with all abstract classes\". Does someone know the rationale for this?

5条回答
  •  难免孤独
    2021-02-09 06:21

    I always understood Interface-Driven Design (IDD) to involve the following steps in creating a concrete class (in its purest form, for non-trivial classes):

    1. Create an interface to describe the properties and behaviours your objects must exhibit, but not how those should function.
    2. Create an abstract base class as the primary implementation of the interface. Implement any functionality required by the interface, but which is unlikely to differ between concrete implementations. Also provide appropriate default (virtual) implementations for members which are unlikely (but possible) to change. You can also provide appropriate constructors (something not possible at the interface level). Mark all other interface members as abstract.
    3. Create your concrete class from the abstract class, overriding a subset of the members originally defined by the interface.

    The above process, while long-winded, ensures maximum adherence to the contract you initially lay down, while minimising redundant code in alternative implementations.

    This is why I would generally pair an abstract class with an interface.

提交回复
热议问题