When are interfaces needed?

前端 未结 15 1540
日久生厌
日久生厌 2020-12-13 00:56

(In the context of .NET for what its worth)

I tend to not use inheritance and rarely use interfaces. I came across someone who thinks interfaces are the best thing

15条回答
  •  再見小時候
    2020-12-13 01:18

    Interfaces don't force classes to use methods. They force implementing classes to implement all methods, but that's a different matter.

    I like the way that interfaces separate out API from implementation. Admittedly this is also done with access modifiers, but interfaces make it clearer. More importantly, interfaces also make mocking easier - which means that you can unit test the classes which depend on the interface even before you've ever implemented it.

    And yes, this means I often end up with an interface which only has a single production implementation. That isn't a problem in my view, because I've gained testability.

    On the other hand, I don't write an interface for every class. I like to write interfaces where an object is essentially providing a service - authentication, data access etc. Plain data objects (even with significant behaviour) aren't as useful in terms of interfaces, IME.

提交回复
热议问题