When are interfaces needed?

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

    According to wikipedia,

    The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time (this is called late binding or dynamic binding).

    That's what makes interfaces so useful.

    "The guy above says he creates another interface to handle the new member(s). Nothing breaks."

    I'm just guessing here, but it sounds like this guy comes from an old school COM background (I could be wrong, of course!). Makes me cringe to think of all of the code I've worked on where I've seen things like this:

    • IWidgetManager
    • IWidgetManager2
    • IWidgetManager3

    That's not a good way to work with interfaces. In my experience, I've seen both extremes: fear of changing interfaces to the point where new interfaces are created whenever new members are added, or not using interfaces at all and having a product that suffers from a high degree of coupling. You need to find a good balance. It isn't always the end of the world to change an interface.

    What is the size of the project you're working on? It can be hard to see the benefit of interfaces if it is a relatively small size project. If, on the other hand, it's a project with several hundred thousand lines of code and is composed of many modules, the benefits become far more apparent.

提交回复
热议问题