Is it the best practice to extract an interface for every class?

后端 未结 13 2511
我在风中等你
我在风中等你 2020-12-04 17:43

I have seen code where every class has an interface that it implements.

Sometimes there is no common interface for them all.

They are just there and they are

相关标签:
13条回答
  • 2020-12-04 18:06

    There's no practical reason behind extracting Interfaces for each class in your project. That'd be an over-kill. The reason why they must be extracting interfaces would be the fact that they seem to implement an OOAD principle "Program to Interface, not to Implementation". You can find more information about this principle with an example here.

    0 讨论(0)
  • 2020-12-04 18:07

    There might be, if you want to be sure to be able to inject other implementations in the future. For some (maybe most) cases, this is overkill, but it is as with most habits - if you're used to it, you don't loos very much time doing it. And since you can never be sure what you'll want to replace in the future, extracting an interface on every class does have a point.

    There is never only one solution to a problem. Thus, there could always be more than one implementation of the same interface.

    0 讨论(0)
  • 2020-12-04 18:12

    Interfaces define a behaviour. If you implement one or more interfaces then your object behaves like the one or other interfaces describes. This allows loose coupling between classes. It is really useful when you have to replace an implementation by another one. Communication between classes shall always be done using interfaces excepting if the classes are really tightly bound to each other.

    0 讨论(0)
  • 2020-12-04 18:15

    The interfaces are good to have since you can mock the classes when (unit-) testing.

    I create interfaces for at least all classes that touches external resources (e.g. database, filesystem, webservice) and then write a mock or use a mocking framework to simulate the behavior.

    0 讨论(0)
  • 2020-12-04 18:17

    I don't think it's reasonable for Every class.

    It's a matter of how much reuse you expect from what type of a component. Of course, you have to plan for more reuse (without the need to do major refactoring later) than you are really going to use at the moment, but extracting an abstract interface for every single class in a program would mean you have less classes than needed.

    0 讨论(0)
  • 2020-12-04 18:17

    Why do you need interfaces? Think practically and deeply. Interfaces are not really attached to classes, rather they are attached to services. The goal of interface is what you allow others to do with your code without serving them the code. So it relates to the service and its management.

    See ya

    0 讨论(0)
提交回复
热议问题