Designing classes for containers or collections

When we have more complex containers or collections, we have more complex design decisions to make. One question is about the granularity of our shelved objects.

When we have an object, such as Blog, which is a container, we can persist the entire container as a single, complex object on our shelf. To an extent, this might defeat the purpose of having multiple objects on a shelf in the first place. Storing large containers involves coarse-grained storage. If we change a contained object, the entire container must be serialized and stored. If we wind up effectively pickling the entire universe of objects in a single container, why use shelve? We must strike a balance that is appropriate to the application's requirements.

One alternative is to decompose the collection into separate, individual items. In this case, our top-level Blog object won't be a proper Python container anymore. The parent might refer to each child with a collection of keys. Each child object could refer to the parent by the key. This use of keys is unusual in object-oriented design. Normally, objects simply contain references to other objects. When using shelve (or other databases), we can be forced to use indirect references by the key.

Each child will now have two keys: its own primary key, plus a foreign key that is the primary key of the parent object. This leads to a second design question about representing the key strings for the parents and their children.

The next section shows how to refer to objects via foreign keys.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset