Useless interfaces

后端 未结 25 1491
南笙
南笙 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:40

    A number of the other answers mention "working with others", and this is certainly a concern. A project with 10 programmers is going to have to approach things differently than a project with one, and unfortunately, laying out a software architecture in such a way that multiple people can contribute to it is something people seem to always learn the hard way.

    Can anyone suggest any good books or articles?

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

    An example of where it may make sense to create an interface for a single class is (as others have mentioned) when we might expect it to be extended.

    For example, if I've got a tracking tool that I'm building for my own personal use, that'll use SQL server. I'm creating an interface for the DB abstraction even though the DB methods are contained to a single class. The reason is that it will make the job of extending the application to use other DB platforms simpler.

    I realize that similar types of abstractions already exist in the .NET framework, but I figured this was a pertinent example.

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

    Some people always create interface because they can be auto generated, so they are justifying working time creating interfaces, no matter if they are really used or not.

    For example, sometimes developers are evaluated per line of code written, so it make sense to use interface.

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

    Because they miss C++ header files?

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

    Yes, especially with Delphi.

    If you have an interface reference to a object then you get reference counting automatically. So it is really common to have an interface with only one implementation when you want the object to be cleaned up automatically. Reference counting is better than garbage collecting since the object's destructor is called as soon as the last reference either goes out of scope or is no longer referencing it.

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

    I often do this and for several reasons:

    1) It allows you to specify which features of a class are actually being used outside the class. This tells you which features you always need to support as long as that interface remains unchanged. This allows you to have other public methods in that class for whatever reason (to support other interfaces or for other objects that have an instance of the object and refer to it by the actual class name as opposed to through the interface).

    2) It also trims down the list provided through intellisense to only the features supported by the interface.

    3) And as stated above, it's useful for unit testing and mocking frameworks.

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