Reality is a perception. Perceptions are not always based on facts, and are strongly influenced by illusions. Inquisitiveness is hence indispensable

Thursday, September 25, 2008

Global Singletons, Good and Bad

I am just quoting my opinion someone elses article. The actual article can be found at:
singletons-are-pathological-liars


Why is global bad? Yeah, I know what your are thinking, and no, I am not joking. There are certain languages like JS which are quite powerful and yet have limited ability to comeup with walls (modularity).

Global is bad because:
a. It causes namespace conflict
b. It exposes the state in a unwarranted fashion

When it comes to Singletons
a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue
b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of.

Now if they are designed to act as application cache, you may see a lack of adequate cohesion. So what do we do! Using the pathelogical lies analogy, hide the unpleasant details, in private methods or in interfacing Adaptors (IOC). Make sure that these kinds of singletons are restricted to above sections of code and for the rest of application they become person-nongrata. Finally when you test the application, you won’t see the singletons. Not fool proof, but just makes it a wee bit difficult to accidentally modify things.

If we are exposing state of instance to Singletons in any other way, it is a bad OO design.

Quoting Dalai Lama, “Know your rules well, so that you can break them”.

No comments:

Popular Posts

Labels

About Me

Well for a start, I dont' want to!. Yes I am reclusive, no I am not secretive; Candid? Yes; Aspergers? No :). My friends call me an enthusiast, my boss calls me purist, I call myself an explorer, to summarise; just an inquisitive child who didnt'learn to take things for granted. For the sake of living, I work as a S/W engineer. If you dont' know what it means, turn back right now.