When are interfaces needed?

前端 未结 15 1520
日久生厌
日久生厌 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:26

    The primary use of an interface is to allow the variation of implementation allowing code to be switched at runtime. There are a number of reasons/rationale for doing this.

    In the past some have argued that every class in the system should have an interface, but this is widely recognized as overkill. Interfaces are now used where instances of classes either can change as part of the system operation (to represent state): GoF patterns like Strategy and Command capture this use, and/or parts of the system need to be replaced for testing (ie. dependency injection). If developers are following test-driven development practices the key infrastructure objects will have interfaces. This allows tests to make "mocks" of these objects to test the system's flow-of-control. There is a relationship between this use of interface and the Liskov Substitution Principle (one of the principles of OO design)

    A further use for interfaces which is less concerned with what is available to the caller, is the marker interface. Which is a way of associating metadata with the class definition. This may affect how the system views the object (for example allow it to be Serialized) or it might just serve as documentation.

提交回复
热议问题