1

Suppose you have a program that should read from a config file the settings for your program. Would you implement them with a singleton class that stores them, a class with static properties for each setting, o global variables inside a namespace? Or probably something better?

In my case I'm implementing them with globals in a namespace, although I've been taught to never use globals for anything, since I've read that the Singleton pattern is now considered even worse than them.

LihO
  • 37,789
  • 9
  • 89
  • 156
Adrián Pérez
  • 2,086
  • 4
  • 21
  • 32

2 Answers2

3

I would implement them in a separate class or module (similar to boost.program_options) and propagate them in the rest of the code base through dependency injection and parameter values.

To the degree that these values do not change, you can put them in (either) an options file or as default parameter values and forget about them.

This would allow for running with different defaults without any change to the code base and allow you to use different defaults/mock data when running tests.

utnapistim
  • 24,817
  • 3
  • 41
  • 76
0

I would use a singleton that returns some sort of container containing all the attributes i need to configure my program. IMO as long as the singleton has not internal states, that influence the call of singelton member, theres no problem in using the pattern. With stateless i mean that the a call to a singleton member should always produce the same result, with a given set of parameters, no matter what. This way one can guarentee that two calls at different locations in the program do not affect the programm in different ways.

Tomas Longo
  • 85
  • 1
  • 7