laserkestrel / starmap

Other
0 stars 0 forks source link

LoadConfig DRYness #8

Open laserkestrel opened 10 months ago

laserkestrel commented 10 months ago

Here are some improvements you can make to make the code more DRY (Don't Repeat Yourself) and reduce redundancy:

Create a Helper Function for Validation:

You can create a helper function to handle the validation of keys and their types in a more concise way. This will eliminate repetitive code for each configuration value. Here's an example of such a function:

template <typename T>
bool validateKey(const json& config, const std::string& key, T& value, const std::string& type)
{
    if (config.contains(key) && config[key].is<T>())
    {
        value = config[key].get<T>();
        return true;
    }
    else
    {
        std::cerr << "Error: Missing or invalid " << key << " in the config file (Expected " << type << ")." << std::endl;
        return false;
    }
}

Use the Helper Function for Validation:

You can now use this helper function in your loadFromFile method for each configuration value. Here's an example for scaleFactor:

if (validateKey(config, "scaleFactor", scaleFactor, "integer"))
{
    // Validation successful, 'scaleFactor' is now populated.
}

Refactor Common Validation Logic:

You can also create a generic template function to handle the parsing and validation of different types of configuration values. This reduces the repetition of code further:

template <typename T>
bool parseAndValidate(const json& config, const std::string& key, T& value, const std::string& type)
{
    if (config.contains(key) && config[key].is<T>())
    {
        value = config[key].get<T>();
        return true;
    }
    else
    {
        std::cerr << "Error: Missing or invalid " << key << " in the config file (Expected " << type << ")." << std::endl;
        return false;
    }
}

Simplify Boolean Parsing:

For boolean values, you can simplify the parsing and validation without the need for the std::string comparison:

bool summaryShowPerProbe; // Change type to bool

if (parseAndValidate(config, "summaryShowPerProbe", summaryShowPerProbe, "boolean"))
{
    // 'summaryShowPerProbe' is now populated as true or false.
}

By using these improvements, you can significantly reduce code duplication and make the validation and parsing of configuration values more concise and maintainable.