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

后端 未结 13 2571
我在风中等你
我在风中等你 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:00

    Let me quote OO guru, Martin Fowler, to add some solid justification to the most common answer in this thread.

    This excerpt comes from the "Patterns of Enterprise Application Architecture" (enlisted in the "classics of programming" and\or the "every dev must read" book category).

    [Pattern] Separated Interface

    (...)

    When to Use It

    You use Separated Interface when you need to break a dependency between two parts of the system.

    (...)

    I come across many developers who have separate interfaces for every class they write. I think this is excessive, especially for application development. Keeping separate interfaces and implementations is extra work, especially since you often need factory classes (with interfaces and implementations) as well. For applications I recommend using a separate interface only if you want to break a dependency or you want to have multiple independent implementations. If you put the interface and implementation together and need to separate them later, this is a simple refactoring that can be delayed until you need to do it.

    Answering your question: no

    I've seen some of the "fancy" code of this type myself, where developer thinks he's SOLID, but instead is unintelligible, difficult to extend and too complex.

提交回复
热议问题