views:

390

answers:

4

Hi In all my projects till now, I use to use singleton pattern to access Application configuration throughout the application. Lately I see lot of articles taking about not to use singleton pattern , because this pattern does not promote of testability also it hides the Component dependency. My question is what is the best way to store Application configuration, which is easily accessible throughout the application without passing the configuration object all over the application ?.

Thanks in Advance

Madhu

+4  A: 

I think an application configuration is an excellent use of the Singleton pattern. I tend to use it myself to prevent having to reread the configuration each time I want to access it and because I like to have the configuration be strongly typed (i.e, not have to convert non-string values each time). I usually build in some backdoor methods to my Singleton to support testability -- i.e., the ability to inject an XML configuration so I can set it in my test and the ability to destroy the Singleton so that it gets recreated when needed. Typically these are private methods that I access via reflection so that they are hidden from the public interface.

tvanfosson
+1, people DO love to create their little rules like "only one exit from a loop" or "no singletons allowed". I'd prefer to be pragmatic rather than dogmatic since dogma leads to people not being able to think for themselves. If you can only have one X object, you should only have one XConfig object.
paxdiablo
Having a single instance of a configuration object is fine and desirable, but it doesn't make using a Singleton to get it good. Using hacks like test specific methods in your actual class aren't good for clean code or tests either.
ColinD
A: 

For that specific situation I would create one configuration object and pass it around to those who need it.

Since it is the configuration it should be used only in certain parts of the app and not necessarily should be Omnipresent.

However if you haven't had problems using them, and don't want to test it that hard, you should keep going as you did until today.

Read the discussion about why are they considered harmful. I think most of the problems come when a lot of resources are being held by the singleton.

For the app configuraion I think it would be safe to keep it like it is.

OscarRyz
A: 

Use dependency injection to inject the single configuration object into any classes that need it. This way you can use a mock configuration for testing or whatever you want... you're not explicitly going out and getting something that needs to be initialized with configuration files. With dependency injection, you are not passing the object around either.

ColinD
A: 

The singleton pattern seems to be the way to go. Here's a Setting class that I wrote that works well for me.

Protagonist