12

I have a large project with a driver part and about 5 libraries doing various associated tasks. Many of the libraries require access to 'global' configuration data which is read from a database at startup by the driver code. By driver I just mean the part which contains the main function.

My idea on how to handle this was to create a config class with a static method to get the config items. Is this the best approach? How else could this be achieved?

eg:

class config { public: static get_item(key); private: static values; }; 

Is singleton design appropriate here?

2 Answers 2

17

The non-singleton way is to create a regular configuration class with regular properties / members, instantiate that object with the correct settings from the database in the driver, and pass the instance to all of the libraries - probably through a std::shared_ptr. This is a common design pattern called Dependency Injection.

That way you avoid all of the potential issues from the singleton design pattern and your code will be more testable as you can instantiate an instance of your configuration class any way you like, with any data, for testing.

4
  • +1, wanted to add that thing about testability to my own answer, but you were quicker. Commented May 7, 2013 at 12:38
  • Slightly OT: Isn't that still a Singleton, just implemented differently? Commented May 7, 2013 at 12:40
  • 1
    @adhominem - no, it's an object for which only a single instance happens to exist, but there's no special machinery around it. Commented May 7, 2013 at 12:45
  • @OliverWeiler - correct, and I really should have referenced that design pattern name in my answer, so I'm adding it now. Commented May 7, 2013 at 14:04
1

I think this is one of the times where a Singleton is actually the correct thing to do.

Regarding the interface of the class itself, you could either do get-by-key-name or have accessors for the individual config values. The latter scheme affords some convenience (IDE completion for one) and allows you to cast the config values to their correct datatypes before using them. It also introduces some separation between the users of the config class and its internal implemntation (the fact that all config values are stored as, say, strings, is an implementation detail the user of the class should not worry about).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.