I recently came across classes that use a configuration object instead of the usual setter methods for configuration. A small example:
class A {
int a, b;
public:
A(const AConfiguration& conf) { a = conf.a; b = conf.b; }
};
struct AConfiguration { int a, b; };
The upsides:
- You can extend your object and easily guarantee reasonable default values for new values without your users ever needing to know about it.
- You can check a configuration for consistency (e.g. your class only allows some combinations of values)
- You save a lot of code by ommiting the setters.
- You get a default constructor for specifying a default constructor for your Configuration struct and use
A(const AConfiguration& conf = AConfiguration())
.
The downside(s):
- You need to know the configuration at construction time and can't change it later on.
Are there more downsides to this that I'm missing? If there aren't: Why isn't this used more frequently?