💾

Serialization

CategoryC++

Overview

Serialization is the process of converting the state of an object into a format that can be stored and reconstructed later.

Goal

Read and write a set of objects from and to memory.

Serializer

The serializer is an interface for serializing data.

The format of the data in depends on the serializer implementation.

Examples of serializers:

Code Generation

With a reflection system where code is generated to build type information, the serialization code can be generated as well.

Inheritance

The inheritance approach:

class ISerializable
{
public:
  virtual void Serialize(ISerializer* serializer) abstract;
};

class MyComponent : public ISerializable
{
private:
  int _int;
  float _float;
  Color _color;

public:
  virtual void Serialize(ISerializer* serializer) override
  {
    serializer->Serialize(“int”, _int);
    serializer->Serialize(“float”, _float);
    serializer->Serialize(“color”, _color);
  }
};

Schema

A different approach is to define a custom schema to describe the data.

Backward Compatibility

Backward compatibility is the ability of newer versions of a program to load data stored from older versions.

Version

You store a version number before the serialized data, and you check the current version to provide different code paths to deserialize the data.

The latest version number is generally defined in the code, and the serializer writes this value for the newly serialized data.

When the definition of the data changes, the version number is incremented.

if (version == 1)
{
    ...
}
else if (version == 2)
{
    ...
}

Forward Compatibility

Forward compatibility is the ability of older versions of a program to load data stored from newer versions.

Versioning is impossible, as it's impossible to predict the new changes related to newer versions.