We have a trivial c++ task to parse a big json file from an http endpoint and then copy the values to a custom local class instance. (In the code below the instance is obj
with setters setField1
, setField2
, etc.)
This code is "simple," but the json response is huge and results in a very big c++ file that does the same thing. However, there are some things to consider, namely different type and setter method names. Below are 3 cases (an int, a bool, and a double), but my code contains this for at least 50 types. How can I modernize the code, make it less error-prone, and take fewer lines of code?
if ( item_[i].HasMember("field1") && item_[i]["field1"].IsDouble()) {
double v = item_[i]["field1"].GetDouble();
if ( v < 0 )
throw CustomException("field1 value invalid");
obj.setField1(v);
} else {
throw CustomException("field1 missing or wrong data type");
}
if ( item_[i].HasMember("field2") && item_[i]["field2"].IsBool()) {
bool v = item_[i]["field2"].GetBool();
obj.setField2(v);
} else {
throw CustomException("field2 missing or wrong data type");
}
if ( item_[i].HasMember("field3") && item_[i]["field3"].IsInt()) {
int v = item_[i]["field3"].GetInt();
if ( v < 0 )
throw CustomException("field3 value invalid");
obj.setField3(v);
} else {
throw CustomException("field3 missing or wrong data type");
}
IsInt
,GetInt
methods, do you have a chance to get them asIs<int>
andGet<int>
methods? Then it would be quite trivial.item_[i]["fieldName"]
on an item that does not have that field ? One step further, what happens when callingGetBool()
on a field that is not abool
? I'd expect the answer to be "an exception" in both cases, then your code could be reduced to a series ofobj.setFieldN(item_[i]["fieldN"].GetType());
, wrapped inside a singletry
/catch
to throw your custom exception.[codereview.se]
to render it as a link to Code Review ;-)