Why Static Methods Are Bad

Disclaimer: I am a firm believer that you should never say never…whoops, just contradicted myself. Well, you know what I mean: Most principles in development are not hard and fast. There are always cases for going against the grain. Every valid principle has an equally valid exception case where disregarding the principle can be advantageous. While I feel there are valid uses for static methods, for the most part I believe they are destructive to a codebase.

Static methods spread dependencies throughout your code making it difficult to test and maintain. I don’t remember who said it, but someone referred to the use of static methods as the “Dependency Broadcaster” pattern. Its very true. Once a method depends upon a class’s static method, it depends upon that class explicitly. You cannot mock the dependency, you cannot inject it…it is hardcoded. This is not good!

Haven’t you heard the statement “Don’t use global variables?” There is a reason not to use global variables or global functions: you can’t immediately see where they are used. Moreover, if you are trying to test something, you can’t replace that global variable without affecting every part of the system that uses it. Dependecies on global variables are hidden. You don’t know what you are affecting when you change them.

Static methods are the “global variables” of the Object-Oriented age. That’s what static means…unchanging…always the same, everywhere…global. Stay away from these when you can. While there are valid uses for static methods, most of the time you can do without them. Use Dependency Injection or some other technique to avoid their use when possible. You will thank yourself later.

This entry was posted in .NET, C#, Design and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>