Useless interfaces

后端 未结 25 1488
南笙
南笙 2020-12-14 01:42

Why would you ever use an interface if you are only going to have one implementation of it?

相关标签:
25条回答
  • 2020-12-14 02:19

    The ability to expand later on in the future.

    0 讨论(0)
  • 2020-12-14 02:21

    Some technologies require you use an interfaces. COM for one. Their you often have just one class implementing your interface.

    0 讨论(0)
  • 2020-12-14 02:22

    One reason could be decoupling: if your classes are used by another developer, you can give him the source code for the interfaces, and keep the implementation detail for yourself.

    If the implementation changes, and the "contract" defined in the interface doesn't, you'll be happy: your interface still describes what the class does, and nobody has to know how it does it.

    0 讨论(0)
  • 2020-12-14 02:23

    To separate the API from the implementation, which is often a good programming practice. It will help with readability, if nothing else. It will also allow someone using your code in the future to provide an alternate implementation of the interface if they so desire.

    0 讨论(0)
  • 2020-12-14 02:23

    If there truely ever is one implementation and only ever going to be one implementation, don't code an interface. (YAGNI).

    However, 99% of the time there is at least two implementations of a class, one real, one used in testing.

    The ease of separating and mocking parts of a system during testing is more than worth the added effort of creating an interface for one class.

    As a side note, and perhaps this is just because I lack some self control, coding against interfaces keeps me a lot more focused when I am working on a particular class. I find myself thinking more of "and this interface I am calling will return/do this" rather than "and this class I'm works like this, it calls x, transforms y, communicates with z, puts the coffee on, fluffs the pillows, integrates n with respect to y and then returns an instance of monkey... wait, what was I doing again?"

    0 讨论(0)
  • 2020-12-14 02:24

    If you are working with a system that allows refactoring, you should only add interfaces if either it is needed for the specification (say, an external API) or if you need multiple implementations. I consider test objects to be valid interpretations, so if you need an interface in order to get it under test, that is a fine use of interfaces.

    Value objects should rarely become interfaces, service objects should frequently become interfaces.

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