Suppose we have built a simple, desktop, single-user application, such as a 2D drafting package. (It might help to think of the “Scribble” tutorial that ships with Visual C++). Suppose too that we have built our application using OO techniques, and represent the graphical objects as a graph of in-memory objects, with one object representing the root of the entire picture.
What we would like, is a painless way to save the entire picture to a disk file, so that it will be there for us tomorrow when we reboot our PC. Before the runtime, each object would have to implement the Serialize (and corresponding Deserialize) method. However, with the runtime, there is really no need to impose this burden on the application programmer. After all, the runtime maintains metadata at runtime that allows serialization code to ‘discover’ the types and values of all fields and properties that make up any object.
So long as the runtime provides a default text formatter (and the current hot favorite is to generate and XML stream), then serializing an entire object graph to a file should be as simple as:
ofstream ofs = new FileStream (“C:\\MyApp.Dat”); TextFormatter fmt = new TextFormatter; fmt.Serialize (obj, ofs);
The obj argument represents the root of the object graph. (Note – this syntax is invented for illustration only. The actual APIs are described earlier – see Section Error! Reference source not found.).
Similarly, in order to start up our App the next day, ideally we need only code a few lines, like this:
ifstream ifs = new FileStream (“C:\\MyApp.Dat”); TextFormatter fmt = new TextFormatter; Obj = fmt.Deserialize (ifs);
Note that the whole point of saving our object graph to a file is so that we can later restore that graph into memory as if no time had intervened between. In order to achieve this aim, it’s clear that we must serialize the entire state of all the objects. We must therefore include every field and every property of each object, regardless of their accessibility – public, protected or private.
It is likely that we will provide at least two Serializer/Formatters – one for text, and one for binary data. In addition, our aim is that ISVs and customers should be given enough information, and supported APIs to enable them to build their own Serializer/Formatters. Therefore, it is likely that each Formatter may prefix each stream with some data that identifies who wrote that stream. This would enable checking when the file came to be Deserialized. Such header information is at the discretion of each Formatter.