We all know about it but there is always an issue how to explain it to a beginner, why static classes are just a no way to go. Of course, you as a software guru can directly point out at least 10 reasons why… “it is not testable”, “it is not object oriented coding”, “you make your code highly coupled”, and so on… Unfortunately, beginners accept them as “very smart reasons”, but they don’t fully understand them. How to explain why static classes are just pure evil?
Very simple example: you want to ask John a question
Our example comes from life. You want to ask your very good friend – John- a question. John is always happy to answer all of them. Unfortunately, sometimes he doesn’t know the answer so he asks his wife – Alice. Stop! now imagine that you want to map this real life situation to your code…
Your classes are like people
John is a class, you as well, and of course John’s wife too. So we have three classes with names “John”, “Alice”, “You”. When you want to ask John a question, you simply launch method on John object. Well, here you can do two things.
You can make your people(classes) like gods!
When you want to ask John a question, you will simply grab a phone and call to him or just ask him if he is nearby. Well, in the real world this is the common way to go. In the coding world you have bigger power! You are able to make your John a god!
When John is a god, you can ask him wherever you are
If you make your John (class) a god (a static class) you will be able, from now on ask John a question no matter in which place you are. This is just great! Imagine that John can be with you in all places you wish him to be. You are watching a movie and John is always sitting next to you, you are having a bath and John is also next to you… well the second example is not so accurate!
When John is a god, he is with you everywhere, also in places you don’t want him to be!
That is general issue with making John a god (a static class). He is everywhere. Your intimacy is revealed. He can always see you and you see him as well.
John’s wife can also ask him a question when you are talking with him
Imagine that you are talking with John, but suddenly, out of nowhere John’s wife cuts in and asks him something in the middle of your conversation. Because John loves his wife very much, your conversation is instantly over and he will happily answer his wife’s question. If this happens once, this is acceptable but because John is a god (static class). John’s wife can ask him whenever she likes. She is really driving you crazy!
John has to became mortal
To save your friendship with John there is only one way to go! John has to become a mortal (regular class). From now on, you will be able to ask him a question only when he is available. You can have him nearby when you meet on a street (you get him as argument to your constructor) or in a pub (you get him as property sets when your observer pattern notices him in the crowd).
Lastly and very importantly, don’t make an mistake and make John’s wife a god!
You can think that John was lousy god so you decided that instead of him, you can make Alice (John’s wife) a god. Imagine that Alice is able to listen about what you are talking having a beer in a pub… well, I think you know what I mean…
General rule – don’t use static classes unless…
There is no other way to do it (to write your code). Having a god (static class) is not bad, but when you talk with him, make sure that no one can disturb you! (take care of singleton pattern issues, because static class is just a singleton).
How would you take care of said… 'Helperclasses' for instance, let's say you're using a language that does not know hexadecimal colors. On the other hand, you want your users to be able to give hexadecimal values as an input. Wouldn't it be perfect to create a static class named to be a 'ColorHelper' to convert hexadecimal values back and forth to colors your application does understand?
As long as your static class does not need to contain knowledge (members/properties) I assume that static classes are real good solutions?
does the same thing hold for static variables?
This is good example when static classes are quite useful. Static classes give you big power therefore you have to use them smartly. Secondly, such classes are not testable well. For instance you have class “You” which has method “AnswerQuestion”. This method uses static class John in such way: John.HelpWithQuestion(). If you now want to test “You” class you will also test “John.HelpWithQuestion” class as well because you cannot mock statics. This is general issue with TDD and static classes. Second issue is that if you have in your team people that don't realize that they should not put there members/properties, this is one of the places where sooner or later they will try to do it. This is the easiest way to solve most of the programming issues. Just put next static variable, change it when you want and you are done.
Summing it up, assuming your statements that this is only for performing some kind of logic, still static classes are inappropriate for TDD. Secondary, it introduces a place in your code, where your junior coders will sooner or later put some nasty properties to solve their problems. When you realize what are the risks, the usage of static classes can only help you.
In my opinion, you shouldn't use static properties. Even you want to implement Singleton pattern then I would use IoC with Singleton configuration for the specific instance.
The only explanation is when you have some resource file that is generated from Visual Studio (or coded) which has static read only properties. Such properties are safe to use because no one will have a chance to overwrite the value.
When I have a moment that I think that there is no other way to go, just to use static class, I usually take a walk and think about it few minutes, talk with team members, because I think that usage of static classes should be very limited.
You make a very good point there. I kind of overlooked the aspect of having junior coders that would just assume some static members, properties, etc right there.
However, I do not entirely agree that you can't test static's. I assume that, as long as you control all inputs, you will always be able to make a prediction. That is, as long as in your example, John is not calling any external data you don't have any control over. (i.e. if it's going to call for a service to give you it random number)
And I actually I think there should be a way of mocking statics, I think it was RhinoMocks that my collegue once worked with. (It's also discribed in this article by the way: http://www.lnbogen.com/HowToMockStaticClassOrSt…) I'm not saying it's the prettiest approach, but it does allow you not to be affraid of statics -too much-.
Some strict guidelines, and maybe a well thought out combination of pair programming and code reviews could make your junior coders in some powerful members of the coding force quite quick though. I like the approach where as long as you control it, you don't need to be 'affraid of it' 😉
Personally I think I would judge every situation individually. Like you said, if you use statics as constants, there shouldn't be much going wrong. But I don't think you should keep yourself from writing certain code as long as it's neat, fairly testable and first of all well maintainable.
Do you think it also might mean that if you have to look too hard for a different solution, you could also accidentily greatly increase the compexity of your code?
(In reality this actually turns out that I don't use a lot of static classes either because I either don't need them, or think the problem at hand could be solved using a different technique with equal or greater quality)
Thank you for your feedback!
You made your point, however the presented example truely makes that you are using in all your code an instance class that is wrapper for the static class. In such case you have already made John a god in 'cage' :). Then such static class can be internal or even more hidden from other classes (other code parts where you will only reach the wrapper, not static class itself).
My post was more about simple usage of static class directly in your execution code, not in infrastructure. Then, when you have 100 calls to static method all over the place, you just lose control.
Regarding juniors and code reviews, coding in pairs – this is the approach that we follow. The worse case is when your senior coders (some of then) don't realize that static classes are commonly evil, and they abuse them, teaching others improper coding.
Of course, fighting with something for several hours just to make it a bit more neat (not static but instance object) is just a waste of time till the issue is just referencing to your coding guidelines (not that static classes will make your application non maintainable).
In my approach I tend to say “static classes are evil” so then, if someone has to use them, he comes and talk. This is the true gain of the whole approach because usually we just need to think together more to find the best solution. Eventually it can happen that we will use static classes, but than we all know why, and we know what are the limitations and risks.
I guess that's a quite a good approach. 🙂 Discussion and overall awareness.
(By the way, thanks for having shared this piece. It was good brainfood. It did bring some awareness of my own coding. Made me think at least)
I guess, if you put it like this, yeah, I never expected to have… allpowerful entities roaming my code.
And you made another good example of something I forgot. It indeed doesn't mean the seniors always code properly. (I'm just glad I've had a few (to my opinion) superb 'mentors'… Seeing as I hope to be graduating from college in 2 months)
Thanks again for your post, I'll be sure to keep reading your blogentries if I can. By the way, good find on LinkedIn 🙂
It was really nice discussion. I hope to talk with you soon.
With regards,
Maciej Gren
Nicely explained.
adding to that: If we want only one instance of a particular class, instead of making it static, we can use 'Singleton' pattern.
Hi Veera,
exactly, you are right, that would be the approach we should follow if we want to avoid using static classes. I am curiouse, how would you implement this Singleton pattern without using static keyword in it? (I have found http://www.yoda.arachsys.com/csharp/singleton.html as reference but they are using even in their most robust example, static keyword). Is it possible to avoid it? Should we bother with that?
i don't bother about static in singelton implementation. something just has to hold the reference to avoid GC of the instance.
one major problem i have in general with singeltons is that i have to explicitly dispose the objects, because of statics. therefor collaborators have to have knowledge of the livetime of the other objects and that's bad.
there is a lot of inspiring code which solves such problems in ninject or other ioc containers.
“weakreference” is a good keyword 😉
Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://less-accurate.com/
Here elaborates the matter not only extensively but also detailly .I support the
write's unique point.It is useful and benefit to your daily nrtrsmitters.com life.You can go those
sits to know more relate things.They are strongly recommended by friends.Personally
Here elaborates the matter not only extensively but also detailly .I support the
write's unique point.It is useful and benefit to your daily life.You can go those thefer.net Like-Acer tiny let-lands iamateacherithink
sits to know more relate things.They are strongly recommended by friends.Personally
I feel quite well.
I totally agree the standpoint of upstairs, and I believe this will be a trend. I often come this forum , rom here I learn much and know the newest tide! the content here constantly update shoe and I love it! Another I know some websites which often update their contents, you guys should browse if you are free.http://www.assure-every.com
I like writing, hurriedly, not that you are not
http://www.oantcogs.com
I am also a XX fan who really like this! I also like XX, and purchase lots of it every time, like-minded friends can have a look ,we can communicate by the way~~
This comment is pretty late so I don’t know if it’ll get seen.
Does this article not just apply to public static members rather than private ones?
I’m interested because I’m working on a small game engine which constructs objects out of xml config files, populating them with lists of instructions and properties and then, when reading the appropriate list of instructions calls, via a public static function (though it would be trivial to make it non static as I know exactly where it gets called), various private static functions. The private functions are used to operate on my game objects, moving their positions, checking collisions and so on. They are all given the same parameters, the primary game object, a secondary game object (for example, another object being collided with, or sometimes, null) and an object with any parameters.
I suspect by now there are some people who have spat their coffee out at the screen in disgust, but I can’t really see any reason why this would be a flawed approach. It allows me to treat any game object equally and gives me great flexibility in how I describe their behavior.
If this is a terrible practice could some one please clarify why a little more?
Many thanks.
Thanks. You explained the subject in a different way.
technically correct AND entertaining! Nicely put!
Yeah but what if john is single?