Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way of sharing a configuration object across classes?

Tags:

c++

Let us say that I have the classes M, A, B, C. M is the main class of my application (that is the one that does most of the job) and has this structure

class M {
  public:
    // Something here.
  private:
    Conifg config;
    A a;
    std::vector<B> bs;
    const C* c;
};

In a main I create an instance m of class M and I want to set my config object, say by reading it from a file. The configuration object is nothing special, it could be a protocol buffer or a simple struct.

Now, I want a, b and c to be able to access the config object, because there are some global settings that they need. These settings are global, they do not change, and are the same for each instance of A, B and C (and M). What I am currently doing, is having a static field in each class A, B and C and I am setting a copy of the configuration object for each instance of these classes. I do not want these classes to know of the existence of M. Is this the best solution? Should I perhaps think of a global config variable?

like image 213
stefano Avatar asked Jul 11 '11 17:07

stefano


3 Answers

Just pass the Config object to the A, B and C constructors (specifically, pass a reference to the Config object which is stored in M.

That gives you:

  • testability (you can easily swap out the config object for testing purposes
  • ease of reuse (you don't have "invisible" dependencies on globals that just have to be there. All A, B and C needs in order to exist are what they're given in their constructors
  • flexibility (you can create different config objects to pass to different classes, if you need to)
  • readability, because the person reading your code doesn't have to wonder "where does the config object come from? Who else might have changed it? Can I be sure it's been initialized at this point?". The classes A, B and C are self-contained, and can be read and understood in isolation.

But whatever you do, don't use a singleton, and try to avoid static/global data in general.

like image 146
jalf Avatar answered Nov 20 '22 07:11

jalf


I would advice you to use an additional static class for configuration, instead of static fields in all the classes, where you include its header in the places you want.

Implement a static constructor where you initialize all the data you want in the static members. I think this would be a better solution.

like image 4
Rolice Avatar answered Nov 20 '22 07:11

Rolice


I personally would rather somehow pass that config object to A B C than use global/static objects. What about passing it (it's reference) as an argument upon construction of a b c, or setting it later via set_config() call?

like image 4
knightmare Avatar answered Nov 20 '22 07:11

knightmare