如何应对TDD接口过度使用? [英] How to deal with interface overuse in TDD?

查看:124
本文介绍了如何应对TDD接口过度使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当我做TDD它通常会导致一个非常大量的接口。对于具有相关性类,它们是通过构造函数注入的通常方式:

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 usual manner:

public class SomeClass
{
    public SomeClass(IDependencyA first, IDependency second)
    {
        // ...
    }
}

其结果是,几乎每一个类将实现一个接口。

The result is that almost every class will implement an interface.

是的,代码将被分离,并可以隔离很容易测试,但也会有间接的额外的水平,只是让我觉得有点...不安。东西感觉不对。

Yes, the code will be decoupled and can be tested very easily in isolation, but there will also be extra levels of indirection that just makes me feel a little...uneasy. Something doesn't feel right.

可以在不涉及这种大量使用的接口?

Can anyone share other approaches that doesn't involve such heavy use of interfaces?

如何是你们的其余部分在做什么?

How are the rest of you guys doing?

推荐答案

您的测试告诉您重新设计课程。

Your tests are telling you to redesign your classes.

有很多时候你无法避免将复杂的合作者需要被存根,使你的类测试的,但你应该想办法为他们提供的输出这些合作者,而不是的,想想你如何能重新安排它们之间的相互作用,以消除复杂的依赖关系。

There are times when you can't avoid passing complex collaborators that need to be stubbed to make your classes testable, but you should look for ways to provide them with the outputs of those collaborators instead and think about how you could re-arrange their interactions to eliminate complex dependencies.

。例如,而不是提供一个 TaxCalculator中 ITaxRateRepository ,获得这些(在 CalculateTaxes 击中数据库)创建 TaxCalculator中实例前值,并为他们提供给它的构造:

For example, instead of providing a TaxCalculator with a ITaxRateRepository (that hits a database during CalculateTaxes), obtain those values before creating your TaxCalculator instance and provide them to its constructor:

// Bad! (If necessary on occasion)
public TaxCalculator(ITaxRateRepository taxRateRepository) {}

// Good!
public TaxCalculator(IDictonary<Locale, TaxRate> taxRateDictionary) {}



有时,这意味着你必须做出更大的变化,调整对象生存或代码重组大片,但我经常发现低洼的水果,一旦我开始寻找它。

Sometimes this means you have to make bigger changes, adjust object lifetimes or restructure large swaths of code, but I've often found low-lying fruit once I started looking for it.

有关的为减少对依赖你的依赖的技术出色的综述,请参见消除模拟模式

For an excellent roundup of techniques for reducing your dependency on dependencies, see Mock Eliminating Patterns.

这篇关于如何应对TDD接口过度使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆