Generating surrogate keys for objects

One way to generate unique surrogate keys is to use an integer counter. To be sure that we keep this counter properly updated, we will store it in the shelf along with the rest of our data. Even though Python has an internal object ID, we should not use Python's internal identifier for a surrogate key. Python's internal ID numbers have no guarantees of any kind.

As we're going to add some administrative objects to our shelf, we must give these objects unique keys with a distinctive prefix. We'll use _DB. This will be a class name for the administrative objects in our shelf. The design decisions for these administrative objects are similar to the design of the application objects. We need to choose the granularity of storage. We have two choices:

  • Coarse-grained: We can create a single dict object with all of the administrative overheads for surrogate key generations. A single key, such as _DB:max, can identify this object. Within this dict, we could map class names to the maximum identifier values used. Every time we create a new object, we assign the ID from this mapping and then also replace the mapping in the shelf. We'll show the coarse-grained solution in the following Designing a class with a simple key section.
  • Fine-grained: We can add many items to the database, each of which has the maximum key value for a different class of objects. Each of these additional key items has the form of _DB:max:class. The value for each of these keys is just an integer, the largest sequential identifier assigned so far for a given class.

An important consideration here is that we've separated the key design from the class design for our application's classes. We can (and should) design our application objects as simply as possible. We should add just enough overhead to make shelve work properly, but no more.

Let's see how to design a class with a simple key.

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

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