Saving object graphs to file: CodeGen and Executable Graphs

time to read 3 min | 585 words

I need to save and load an object graph to a file.  A pretty routine task, but this time I thought I would dedicate a little thought to this. I need to support a flexible structure that allows saving objects that I don’t know about right now. I’m mostly free to develop the persistence layer any way I want it. My first thought was to try to use Active Record to persist it all to a SQLite database. But I need to support objects with inheritance that I don’t know about in advance. I suppose that I can solve this issue with Table Per Class approach, but I want to reserve this approach for later, mainly because this would mean generating the schema dynamically. I thought that XML Serialization would be easiest, but I run into problems with generics and serializations of interfaces, which I tend to use heavily.

Another issue that I run into is object identity. Here is the simplest example:

Before Serialization:

After Serialization (bad – disconnect in the graph):

  

U0 and U2 points to the same instance of U1

U0 and U2 points to different instances of U1

I couldn’t find a way to persist the first graph and get it back without doing some work that I would rather avoid. I have done some XML Serialization in the past, but I never done anything that cared about object identity. Using Active Record would solve this problem, but this brings me to the dynamic schema problem that I want to avoid if I can.

 

Right now I’m thinking about saving it in an executable format. The idea is to generate (using Code DOM) the actions that are needed to create the graph on save, and on load to compile and run the code to get the live object graph. For instance, take this graph:

 

 

This can be saved as this code:

 

Node u0 = new Node(),  u1 = new Node(), 2 = new Node();
u0.To(u1);
u0.To(u2);
u2.To(u1);
u1.To(u0);

 

There is code generation in this project anyway, so I’m not introducing something completely foreign. This is an intriguing concept for me, since it means that saving the file is quite complex, but the richness of the file format is unparallel.