Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 984
Ryu Avatar asked May 20 '09 15:05

Ryu


1 Answers

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.

like image 52
tanascius Avatar answered Sep 19 '22 05:09

tanascius