是否应该避免使用静态类,因为它会使依赖注入变得困难? [英] Should static classes be avoided because it makes Dependency Injection Difficult?

查看:133
本文介绍了是否应该避免使用静态类,因为它会使依赖注入变得困难?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

负责创建一组核心"库的人创建了一组静态类,这些类提供了从日志记录,审计和常用数据库访问方法中获得的各种实用程序.

Somebody tasked with creating a "Core" set of libraries created a set of static classes providing all sorts of utilities from logging, auditing and common database access methods.

我个人认为这很讨厌,因为我们现在有一组核心库,这些库很难测试,因为我无法模拟/存根这些类或对它们的构造函数进行任何注入.

I personally think this stinks because we now have a Core set of libraries that are hard to test because I can't mock / stub these classes or do any injection into their constructors.

我想我可以使用TypeMock将其存根,但是我宁愿免费使用它.

I suppose I can use TypeMock to stub these out but I'd rather do it for free.

您怎么看?

编辑

如果您不认为它们很难测试,可以举个例子说明如何对其进行测试.这些静态类实例化其他类型来执行其功能.

If you don't think they're hard to test could you give an example of how you would test them. These static classes instantiate other types to do their functions.

推荐答案

不一定要避免使用静态类(方法),只要它们没有隐藏的依赖关系即可.当然,您可以将依赖项传递给静态方法-不应将其存储在内部并修改以后调用的行为.
在这种情况下,对它们进行测试也应该没有问题.

Static classes (methods) do not necessarily have to be avoided as long as they have no hidden dependencies. Of course you can pass dependencies into a static method - it just should not be stored internally and modify the behaviour of later calls.
There should be no problem to test them in this case, too.

但是我对您提到的案件也有不好的感觉.我知道其中一些静态的包装"实用程序类-在大多数情况下,它们确实很臭:)

But I have a bad feeling about the cases you mentioned, too. I know some of these static "wrapper" utility classes - and in most cases they really stink :)


也许我应该澄清一下.我只会将静态类/方法用于非常小的杰出任务.当静态类开始初始化依赖项时,当然应该避免使用它们.如果您无法测试这些静态类,那么它们已经有太多工作要做.


Maybe I should clarify. I would use static classes/methods only for very small distinguished tasks. When static classes start to initialize dependencies they certainly should be avoided. If you can't test these static classes they already have a too big job to do.

此问题的第一个答案中,有人反对您提到的静态类.

In the first answer of this question are the arguments against static classes as you mentioned.

这篇关于是否应该避免使用静态类,因为它会使依赖注入变得困难?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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