My head is swimming from all the crazy comments about this topic. So...here is my GUT feeling and as always remember unsolicited advice is worth what you paid for it...nothing.
1. Coming from C and C++ world globals, statics, and the like are dangerous and thus discouraged...why: un-managed memory not managed correctly can cause memory leaks and crazy bugs.
2. Yes, we used it in C and C ++ but had to be VERY CAREFUL mostly to communicate metrics and state to multi-threaded systems that want to know what other threads are "doing"...like load balancing and thread management. Remember this is 15-20 years ago...
3. In the Java and C# .net world of managed memory today such memory management FEARS are mostly gone and we have very robust thread management frameworks that do all of this "book keeping" for us...so...now what?
4. "Pro-Static" code optimizers like ReSharper suggest you use Statics and such whenever possible...I am guessing for performance in .net but I dont really know...thing about it...allocating memory and de-allocating it still takes up cycles you dont have to spend in a Global space.
5. Some kinds of desired behaviors like state machines need a monostate or singleton pattern to be robust and reflect the desired behavior ( monitoring and persisting state inter-process ) with the least amount of code and maximum performance. If you forbid this kind of persistence you would have to persist it in some other fashion like FILE IO or a Database hit...and you can kiss your performance goodbye.
6. Google discourages Singletons and monostate and if Google doesnt do this then we wont. Well, I am guessing if you REALLY dig into Google code you will see the use of these patterns when it makes the most sense. I will wait to see if someone from Google pipes in on this comment but I doubt they will.
7. Testability...test, test and test some more. For some reason people comment that the Singleton pattern kills testing...I am still trying to figure that one out as the singleton pattern is used in scenarios where its o.k. to have persistence so the tests reflect how the code would behave in production. If the singleton causes erratic behavior then that screams this is a bad pattern and you should remove it. So...remove the singleton.
Let pragmatism guide your developer thoughts and keyboard actions and dont bang your head on state persistence if THATS WHAT YOU NEED AND WANT. Use a clean Singleton or Monostate class and go home to spend more productive time with your family and friends.
0 comments:
Post a Comment