How to deal with interface overuse in TDD?

前端 未结 4 1174
不思量自难忘°
不思量自难忘° 2021-02-01 17:30

I\'ve noticed that when I\'m doing TDD it often leads to a very large amount of interfaces. For classes that have dependencies, they are injected through the constructor in the

4条回答
  •  一向
    一向 (楼主)
    2021-02-01 18:03

    If you are feeling uneasy about the number of interfaces being passed into a particular class; then it is probably a sign that you are introducing too many disparate dependencies.

    If SomeClass depends on IDependencyA, IDependencyB, and IDependencyC, this is an opportunity to see if you can extract out the logic that the class performs with those three interfaces into another class/interface, IDependencyABC.

    Then when you are writing your tests for SomeClass, you only need to mock out the logic that IDependencyABC now provides.

    In addition, if you are still uncomfortable; maybe it is not an interface you require. For example, classes that contain state (parameters being passed around, for instance) could probably just be created and passed around as concrete classes instead. Jeff's answer alluded to this, where he mentions passing into your constructor ONLY what you need. This provides less coupling between your constructs and is a better indication of the intent of your class's needs. Just be careful passing around data structures (IDictionary<,>).

    In the end, TDD is working when you get that warm fuzzy feeling during your cycles. If you feel uneasy, watch for some of the code smells and fix some of those issues to get back on track.

提交回复
热议问题