Why prefix C# interface names with an “I”

前端 未结 18 1611
清歌不尽
清歌不尽 2021-02-01 03:13

What is the rationale behind this naming convention?

I don\'t see any benefit. The extra prefix just pollutes the API.

My thinking is inline with Konrad\'s respo

18条回答
  •  悲&欢浪女
    2021-02-01 03:37

    TL;DR - Extracting interface IFoo from class Foo is common in SOLID decoupling, especially for Unit Testing purposes

    To me the dual convention of class Foo implementing interface IFoo (especially if both are in the same assembly) conveys a specific intention that:

    • Coupling on a dependency to a Foo should always be indirect, through the corresponding IFoo interface (and likely to be injected via an IoC container)
    • The initial design of IFoo is a proprietary, non-reusable interface specifically to allow classes dependent on Foo to mock out this dependency during unit testing.
    • Beyond the above, a reader doesn't need to infer any additional intelligence in the design of the IFoo interface
    • Conversely, if multiple concrete implementation classes of IFoo are required at a later point, that proper interface segregation design will need to be retrofitted into the hierarchy.

    Rationale

    In order to be able to Mock or Stub out a class, a widely accepted best practice in Unit Testing is to decouple dependencies between classes only via interfaces. This interface decoupling will also be done to classes which would otherwise never had a design requirement for polymorphicism (i.e. only one such implementation would have existed, were it not for the need for unit testing).

    As a consequence, the refactoring and reuse of these interfaces (e.g. the Interface Segregation Principal of SOLID) isn't frequently applied to such 'mockable' interfaces - there is often a 1:1 correlation between the public methods, properties and events of a 'mockable' class (Foo) and its decoupled interface IFoo (similar to the COM-era automatic interfaces in VB).

    Tools such as VS and Resharper can make extracting such public symbols from a class into a separate interface trivial, as an afterthought.

    Further, if we consider that Mocking frameworks like Moq allow definition of implementations of the interface on-the-fly, we need not waste effort naming the concrete test double implementation class.

提交回复
热议问题