我正在重构遗留代码库。他们有 100 多个公共(public)配置变量和 90 多个方法用于单个类中的功能。我正在根据特征将大类分解为多个小类。
由于这些配置变量是从配置文件中读取并设置为这些变量的,因此我最终编写了很多 getter 和 setter 方法。
拥有这么多 setter 和 getter 而不是直接赋值,这是一个好的设计吗?
欢迎任何好的设计建议。
下面是一个代码片段
编辑:
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;
...
最佳答案
Is this is a good design to have so many setter and getters instead of direct assignment?
使用简单的
struct
绝对没有错s 用于存储数据:struct SomeData
{
std::string some_name;
int some_value;
float another_value;
}
自从
struct
成员默认为 public
然后你可以简单地写:SomeData mydata;
mydata.some_name = "a name";
...
std::cout << mydata.some_value;
关于C++:处理许多配置变量的设计建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59949139/