Last Updated: February 25, 2016
· kbilsted

Don't use static

Never use the keyword static. Well of course when you are making extension methods. Otherwise don't.

Statics are hard-coding your dependency and killing OOP (you don't operate with instances). Instead use dependency injection.

Caches are a seemingly naturally implemented using statics. Don't! You get more flexibility by avoiding this implementation strategy and you can let some one else handle the eviction strategy. Often that some one has a better idea about the eviction strategy based on the use-scenario rather than a generic cache class.

Sometimes I see people make method static when the methods do not access state on the object. Resharper also encourages you. Again don't follow this practice. If your method is not accessing any state on the object, it may be a hint that the method does not belong to that class. Don't make such methods static as they will hurt you when the code evolves.

Configuration is often tutored at candidates for static. Check out the project https://github.com/kbilsted/StatePrinter which doesn't use static for configuration. This allows me to use different configurations when running my tests in parallel.

Say Thanks

6 Responses
Add your response


I won't say don't use it, but use it intelligently.

over 1 year ago ·

What do you mean intelligently?please give some examples.

over 1 year ago ·

There is such a thing as "process scope" or "application scope". For example, statically declaring the DI container. Such things are obviously suited for using static.

over 1 year ago ·

Thanks for your feedback. DI is an interesting choice. In fact the modern DI containers such as AutoFac has the notion of scoped dependency configurations and thus the configuration is by no means static. Rather it is instance-based. I'll update the text with an example.

over 1 year ago ·

What if you want to make a class singleton ?

over 1 year ago ·

What would the purpose be for you to make a class singleton? If you need singleton behaviour your are better off using a DI framework and configuring the instance as singleton in the registration part of the DI.

over 1 year ago ·