Should static classes be avoided because it makes Dependency Injection Difficult?

家住魔仙堡 提交于 2019-12-03 12:56:43
tanascius

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 :)

EDIT:
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.

How hard would it be to modify those static classes to utilize Dependency Injection? If you make the DI optional (if possible), you can essentially make a situation where you can use the static classes for mocking, just by properly doing the DI, while not changing any of the "normal" behavior.

Following is from Journal of Object Technology: Decoupling responsibilities from static methods for fine-grained configurability

Static methods pose obstacles to the development of tests by hardwiring instance creation. A study of 120 static methods in open-source Smalltalk code shows that out of the 120 static methods, only 6 could not equally well be implemented as instance methods, but were not, thus burdening their caller with the implicit dependency on these static methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!