C++:处理许多配置变量的设计建议

标签 c++ oop configuration refactoring

我正在重构遗留代码库。他们有 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/

相关文章:

c++ - 标记为 std::memory_order_seq_cst 的单个原子操作是否会在各处触发顺序一致性?

Javascript:如何从类的一个函数中的函数访问类属性

c++ - 创建对象作为私有(private)成员变量与在成员函数中

java - Python:像 Java 中的静态类变量?

java - ConfigFactory ParseFile 通过 Java 系统属性的变量替换进行解析

c++ - 学习c++——从文件中读取数字

c++ - 遍历可能从容器中移除的对象

c++ - 调用指令中的偏移量损坏

configuration - 覆盖 WordPress 多站点的 WP_SITEURL 和 WP_HOME

java - log4j2 不将日志写入文件