Reputation: 21
I m refactoring a legacy codebase. They had 100+ public config variables and 90+ methods for the functionality in a single class. I m in the process of breaking down the large class into multiple small classes based on the features. Since these config variables are read from a config file and set to these variables , i end up in writing a lot of getter and setter methods. Is this is a good design to have so many setter and getters instead of direct assignment? Any good design recommendations are welcome. Below is a code snippet EDIT:
class config {
public:
void Setvalue(int val) {value_ = val;}
int Getvalue(){return value_;}
void SetisEnabled(bool value) {isEnabled_ = value;}
bool GetisEnabled() {return isEnabled_; }
void SetorgCity(string city) {orgCity_ = city; }
string GetorgCity(){return orgCity_;}
void SetorgState(string state) {orgState_ = state; }
string GetorgState(){return orgState_;}
..
private:
int value_;
bool isEnabled_;
string orgCity_;
string orgState_;
string orgCounty_;
string orgName_;
string mytypeval1_;
string mytypeval2_;
string mytypeval3_;
string mytypeval4_;
}
or
class Config
{
int value_;
bool isEnabled_;
string orgCity_;
string orgState_;
string orgCounty_;
string orgName_;
string mytypeval1_;
string mytypeval2_;
string mytypeval3_;
string mytypeval4_;
}
Config sampleConfig;
sampleConfig.isEnabled_ = true;
sampleConfig.value_ = 1234;
...
Upvotes: 1
Views: 268
Reputation: 2244
One possibility is for your config
class to have an operation called, say, initFromConfig()
that initialises all its instance variables from an external configuration file. Doing this will remove the need to have setter operations.
Also,it is more efficient for the getter operations to return const string &
rather than string
.
With the above two changes made, your config
class would look like the following:
class config {
public:
initFromConfigFile(const string & fileName); // initialises foo_ and bar_
const string & getFoo() { return foo_; }
const string & getBar() { return bar_; }
private:
string foo_;
string bar_;
};
Upvotes: 0
Reputation: 27577
Is this is a good design to have so many setter and getters instead of direct assignment?
There's absolutely nothing wrong with using a simple struct
s for storing data:
struct SomeData
{
std::string some_name;
int some_value;
float another_value;
}
since struct
members default to public
you can then simply write:
SomeData mydata;
mydata.some_name = "a name";
...
std::cout << mydata.some_value;
Upvotes: 3