yanet icon indicating copy to clipboard operation
yanet copied to clipboard

Holy crusade against copy-paste while parsing configs

Open 3Hren opened this issue 1 year ago • 0 comments

The problem

We have a bit of strange code in https://github.com/yanet-platform/yanet/blob/d53654af2450a6ed7630a4f6e6a2ac16abe50d17/dataplane/dataplane.cpp#L1772 Here, we parse config file and fill the https://github.com/yanet-platform/yanet/blob/d53654af2450a6ed7630a4f6e6a2ac16abe50d17/dataplane/dataplane.h#L331 using the following pattern:

if (exist(json, "some_key")) {
    configValues[eConfigType::some_enum] = json["some_key"];
}

, but such pattern is prone to copy-paste errors. What if we slightly change the key and check for existing for another one?

I suggest to:

  1. Replace this pattern to a single call using https://json.nlohmann.me/api/basic_json/value/ Then, the code above will transform to something like:
configValues[eConfigType::some_enum] = json.value("some_key", 0); // Or meaningful default value.
  1. Replace the map<enum, uint64> to a named struct.
  2. Decompose it into a separate file.
  3. Write an ADL deserializer nearby.
  4. Then, we won't need for https://github.com/yanet-platform/yanet/blob/d53654af2450a6ed7630a4f6e6a2ac16abe50d17/dataplane/dataplane.h#L127, and can access config values directly.

We can start with dataplane config, but, of course, this can be propagated further to other configs.

The profit

  • Less copy-paste.
  • Slightly faster access, as there is no need to recheck while accessing values. More precisely, this function will be removed:
uint64_t cDataPlane::getConfigValue(const eConfigType& type) const {
	if (configValues.find(type) == configValues.end()) {
		YADECAP_LOG_ERROR("unknown variable\n");
		return 0;
	}

	return configValues.find(type)->second;
}

Alternatives

  • Leave as is.

3Hren avatar Feb 01 '24 08:02 3Hren