我有一個 C 20 程式,其中配置通過 JSON 從外部傳遞。根據“清潔架構”,我想盡快將資訊轉換為自定義結構。JSON 的使用只是在“外環”中顯而易見,而不是在我的整個程式中傳播。所以我想要我自己的Config結構。但我不確定如何以一種安全的方式撰寫建構式,以防止丟失初始化、避免冗余以及將外部庫與我的核心物體分開。
一種分離方法是在沒有建構式的情況下定義結構:
struct Config {
bool flag;
int number;
};
然后在另一個檔案中,我可以撰寫一個依賴于 JSON 庫的工廠函式。
Config make_config(json const &json_config) {
return {.flag = json_config["flag"], .number = json_config["number"]};
}
這寫起來有點安全,因為可以直接看到結構欄位名稱與 JSON 欄位的對應關系。我也沒有那么多冗余。但我并沒有真正注意到欄位是否未初始化。
另一種方法是有一個顯式的建構式。如果我忘記初始化一個欄位,Clang-tidy 會警告我:
struct Config {
Config(bool const flag, int const number) : flag(flag), number(number) {}
bool flag;
int number;
};
然后工廠將使用建構式:
Config make_config(json const &json_config) {
return Config(json_config["flag"], json_config["number"]);
}
我現在只需要指定欄位的名稱五次。并且在工廠功能中,對應關系不清晰可見。IDE肯定會顯示引數提示,但感覺很脆弱。
一種非常緊湊的撰寫方式是擁有一個采用 JSON 的建構式,如下所示:
struct Config {
Config(json const &json_config)
: flag(json_config["flag"]), number(json_config["number"]) {}
bool flag;
int number;
};
That is really short, would warn me about uninitialized fields, the correspondence between fields and JSON is directly visible. But I need to import the JSON header in my Config.h file, which I really dislike. It also means that I need to recompile everything that uses the Config class if I should change the way that the configuration is loaded.
Surely C is a language where a lot of boilerplate code is needed. And in theory I like the second variant the best. It is the most encapsulated, the most separated one. But it is the worst to write and maintain. Given that in the realistic code the number of fields is significantly larger, I would sacrifice compilation time for less redundancy and more maintainability.
是否有一些替代方法來組織它,或者最分離的變體也是具有最多樣板代碼的變體?
uj5u.com熱心網友回復:
但是,我會使用建構式方法:
// header, possibly config.h
// only pre-declare!
class json;
struct Config
{
Config(json const& json_config); // only declare!
bool flag;
int number;
};
// now have a separate source file config.cpp:
#include "config.h"
#include <json.h>
Config::Config(json const& json_config)
: flag(json_config["flag"]), number(json_config["number"])
{ }
干凈的方法,避免間接包含 json 標頭。當然,建構式被復制為宣告和定義,但這是通常的 C 方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445352.html
