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

3

8

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.

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

What do you think?

Edit

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.

Komara answered 20/5, 2009 at 15:30 Comment(1)
I don't think there is anything inherently EVIL with certain types of static methods that are referentially transparent, no hidden dependencies, no side effects, etc. the thing is, in moste cases these methods will lead to low cohesion. they probably belong some place else, like a domain object or a service and so on.Quartus
S
9

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.

Spalla answered 20/5, 2009 at 15:38 Comment(0)
D
1

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.

Damato answered 20/5, 2009 at 16:50 Comment(0)
W
1

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

Whitford answered 5/2, 2014 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.