Tuesday, June 29, 2010

Singletons are for losers and bad frameworks...

I recently read Miško Hevery's postSingletons Are Pathological Liars and had trouble with rationalizing this. For a few days I tried to develop a Singleton pattern that would side step the issue. I tried to make the Singleton have default access and then use a proxy class to access it. You'd have to instantiate the proxy class rather than access the Singleton directly. I called this approach "Proxied Singleton." This was great, except for when the Singleton had dependencies, then it all fell apart. I couldn't wrap my head around getting rid of Singletons.

I couldn't comprehend why you would want to completely get rid of them, they're very useful, then I read a few more of his posts. It seems that he's not wanting to get rid of the idea of a Singleton, just the common pattern used for creating them. Essentially, the getInstance() method is the problem. With the getInstance() method you can make a call to the Singleton from anywhere and this makes the code difficult to test and sometimes hard to comprehend. So, let's do away with this pattern.

Now, how would I make sure that my "singleton" only gets instantiated once... well, I'll let Miško answer that ("Where have all the Singletons Gone?"). Great, we're done here, aren't we...? No...

A lot of my work is in a framework that does not allow me to use the factory idea to create single instances of a class. This framework, which will remain *cough* Adobe Livecycle *cough* nameless..., has no ability for me to use a factory method when the application starts and pass those instances around. The framework does allow me to run code when the application starts, but I have no ability to store or pass anything created there to any other objects. So, now what do I do? I have two options, I stick with the crappy Singleton approach, I try to rig up my "Proxied Singleton" class, or I spam the CEO of Adobe until they make their product better. I opted for the last option and now have a restraining order to go along with my problems. I would go my "Proxied Singleton" route, but it essentially gives no advantage and would confuse other programmers (since it's not a standard design). So back to the crappy Singleton approach, with a slight change.

The biggest drawback of the Singleton approach is in it's limitation of being able to change. So, I'll use dependency injection and never call the getInstance() from within the logic classes. This is not completely safe because there is nothing that would stop getInstance() from being used, but I guess I'll have to take my chances. Good thing there is code review. I'll probably look into Google GUICE or Spring to add in some nice dependency management that is not available in LiveCycle, I mean the nameless framework.

You can look forward to some really specific posts coming up, relating to LiveCycle Custom Components and the SAP Jco.

No comments:

Post a Comment