This discussion is a spin off of
this one.
Origionally posted by Jared Chapman:
The update method doesn't throw a DuplicateKeyException, but should it? When choosing fields that make up the primary key, you choose fields that identify the record as unique, and the fields should not be expected to change. For example, the owner field is the worst possible field to be a primary key, because we expect its value to change. So why not prevent updating a record's primary key fields, and instead instruct the caller to delete the record and create a new one? Just an idea, please feel free to tear it apart.
Origionally posted by Daniel Simpson:
I didn't really feel that any field was sufficient enough to be a primary key, so I decided to test every value in the field (except the field for the customer's id showing that it is booked). And if all of the fields were same after trimming for whitespaces, it would throw a DKE, otherwise it would be considered unique. What do you think?
That's exactly what I'm doing, too. I provide two constructors in my Data class: one that takes a File (to connect to a database file), and the other takes a File and a boolean array (where index n determines if field n should be part of the primary key). So in my DataAdapter, I create an instance of Data by calling the two-arg constructor, passing it a boolean array with each index being true, except the last index which is false. This excludes only the owner field from the primary key.
Now, in my Data class, I have an internal class called Record that holds information about a record (recNo, data, isLocked, etc.). It is only used in my Data class. In this record class, I have provided an implementation of equals and hashcode. The equals method will only compare primary key fields when checking for equality, and the hashcode method also is calculated using only the primary key fields.
I store these Record objects in a map called recordCache, which is, as the name implies, a cache of all records in the database. When I check for DuplicateKeyException, I simply do the following:
A DuplicateKeyException will only occur if the primary key of the record I just created matches the primary key of a record already in the cache.
There is a catch that I just thought of, though.
Let's say that I want to prevent the possibility of updating any of the primary key fields of a record - necessary to maintain the integrity of my hashcode implementation. Easy enough to code. But what happens if the grader tests my implementation of Data using the one-arg constructor (which would specify the database location and use the default primary key of a combination of all the fields in a record)? The entire record will be considered the primary key, and update would always fail. And then maybe I'd fail. And that would be $150 worth of a very bad thing.
Perhaps I need to think about my implementation a little more, eh? Any suggestions?