This is something that has been on my mind for quite some time. I see a lot of APIs being built on static methods and classes. I personally think it’s a huge mistake because of:
- testability: mocking static classes/methods is a very difficult endavour, i have yet heard of one mocking library that allows such kind of things
- readability : when you take a class that heavily relies on some kind of static APIs the dependency is not immediately visible and may cause significant problems in refactoring
The static keyword is definitely overused in most code written in .NET maybe because it’s a path of least resistance….
We don’t have to look very far for an example: let’s take a most obvious and common – HttpContext. Fortunately in that case there is even some help from Microsoft in form of Microsoft.Web.Abstractions.
Most of the time what you really want/need is single instance or per request lifetime and it should be expressed in configuration not in code. It’s a lot easier when you use a brand new shiny asp .net mvc where you can easily plug a container which deals with that kind of things. In webforms it’s not that easy.
That said I’m not totally against statics, they are quite handy in some situations ( extension methods yay). I’m just urging for caution. So be careful.