When are interfaces needed?

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

    Interfaces have many useful situations. When you need to add a specific behavior to a class that can be found across a wide variety of classes, that's a perfect time for an interface. A good example is the IDisposable interface - you have some resource that when you're done, needs to go away in a timely fashion. Is it a database connection? Is it some window handle? Doesn't matter.

    Another example would be when you really don't know how it should be implemented, such as an interface to an object that doesn't exist yet. Perhaps the object should be supplied by a client of your library, or must be implemented by a completely different module not under your control. You can basically design a contract for the methods available on the class.

    That said, I only use them where it's needed. If I can do it with a regular class, or if it's something intrinsic to the particular object, I'll make it a class. There are some advantages to using Interfaces for every class as others have said, but that's so much extra overhead that I don't see a decent net gain on it. Most of the time, I've designed my class structures so that they're flat and wide, with as few dependencies as possible.

    In summary: If you have common functionality required that's implemented dramatically differently, an Interface is just what you need.

提交回复
热议问题