Static keyword is the source of all evil, well almost

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.

I would go one step further. My opinion is that there should never be static methods in your code, unless you have very strong argument behind it. Because of it you make tight coupling between two classes which using it, and as you truly said, you can almost forget about testability.

Extensions are very useful, however, because of their convenience there is a strong desire to put important logic there directly, and keep the state behind them anyway.

You’re right. But doing withouth static constructs isn’t possible. There’s often some kind of point of entry which cannot be solved any other way than with static. Take ServiceLocator for example or any inversion control framework. The point of entry is static in such cases – implicit (via configuration) or explicit (via invoking static method).

BTW. Static constructs are often used out of laziness… but have you heard saying that a good programmer is a lazy one? Which may bring us to the conclusion that a good programmer is the one using static keyword ;-).