Useless interfaces

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

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

25条回答
  •  慢半拍i
    慢半拍i (楼主)
    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?"

提交回复
热议问题