[Solved] Maintaining state of a program


This is not black magic.

The answer is by saving its data. You do this by putting it in a database, or writing data files.

The trick is to write your programs in a way that makes it easy to guarantee that you’ve restored the state you thought you saved.

A common approach is to use serialization. This means that you are able to take your giant data structure and recursively call a ‘Save’ function on it and its contained objects. This is very intuitive if you are taking advantage of object inheritance and polymorphism. Of course, you also write a ‘Load’ function to do the reverse.

You write your data in such a way that it can be read back in. For example, if you wanted to write a string, you might first write its length and then its characters. That way, when you read it you know how many bytes to allocate.

The above approach is pretty standard if you are writing binary file formats. In fact, it’s the philosophy behind chunk-based formats such as AVI.

For text-based, you might choose to serialize your data in popular formats like XML or JSON. But you are only restricted by your imagination.

1

solved Maintaining state of a program