C++ Serialization – Do You Need a Wrapper Function for Short Code?

cserialization

In the early time, maybe just few line code, But I have see too many repeated and messy codes involve serialize/deserialize interference the main logic. So I try to persuade the team members to wrap a function for operations like read/write/update data ,example as:

 void updateCopyTimes(int times)
  { 
    player->getExtendJson["AcopyTimes"] = Json::Value(times);
    player->updateExtendJson();
  }

  int getCopyTimes()
  {
       const int copyTimes = player->getExtendJson["AcopyTimes"].asInt();
       return copyTimes;
  }

The point support my opinion is:

1) With a wrapper function, we can have a good code hierarchy, we can focus on the logic, make the serialize/deserialize clean, not spreading anywhere.

2) Easy to extend, we can easy to modify the program to serialize into a mysql field(int/string/date …), into another mysql json field, easy to add checking code ,with the main logic immune to the modification.

The discommender argue that :

1) In our program , the chance to switch to another serialization format is pretty low, nearly imposible. It's not worthwhile to do it.

2) Wrapping such a function is over-thinking, if we do that, more code we have to write. And if we can finish the job, why bothering yourself ?

3)And most importantly, different developers hard to follow this rule.

So under what condition(operations type, code quantity …), we need such a wrapper function ?

Best Answer

You would need to separate code out into a new function if it makes the code easier to read, reason about or maintain.

This is independent of the number of lines that you would move into the function, but for small sections of code it is a subjective judgement call which version is easier to read.

If you often have comment markers in the code like this

void function_a() {
  some code

  // serialization
  serialization code
  // end serialization

  more code
}

then that is an indication that it would be good to extract the code between the markers into a function of its own.

Related Topic