Is it a good idea to create a custom type for the primary key of each data table?
.net, c#, database, design-patterns
Solution
I wouldn't make a special id for this. This is mostly a testing issue. You can test the code and make sure it does what it is supposed to.
You can create a standard way of doing things in your system than help future maintenance (similar to what you mention) by passing in the whole object to be manipulated. Of course, if you named your parameter (int personID) and had documentation then any non malicious programmer should be able to use the code effectively when calling that method. Passing a whole object will do that type matching that you are looking for and that should be enough of a standardized way.
I just see having a special structure made to guard against this as adding more work for little benefit. Even if you did this, someone could come along and find a convenient way to make a 'helper' method and bypass whatever structure you put in place anyway so it really isn't a guarantee.
Problem
We have a lot of code that passes about “Ids” of data rows; these are mostly ints or guids. I could make this code safer by creating a different struct for the id of each database table. Then the type checker will help to find cases when the wrong ID is passed. E.g the Person table has a column calls PersonId and we have code like: ``` DeletePerson(int personId) DeleteCar(int carId) ``` Would it be better to have: ``` struct PersonId { private int id; // GetHashCode etc.... } DeletePerson(PersionId persionId) DeleteCar(CarId carId) ``` Has anyone got real life experience of dong this? Is it worth the overhead? Or more pain then it is worth? (It would also make it easier to change the data type in the database of the primary key, that is way I thought of this ideal in the first place) Please don’t say use an ORM some other big change to the system design as I know an ORM would be a better option, but that is not under my power at present. However I can make minor changes like the above to the module I am working on at present. Update: Note this is not a web application and the Ids are kept in memory and passed about with WCF, so there is no conversion to/from strings at the edge. There is no reason that the WCF interface can’t use the PersonId type etc. The PersonsId type etc could even be used in the WPF/Winforms UI code. The only inherently "untyped" bit of the system is the database. This seems to be down to the cost/benefit of spending time writing code that the compiler can check better, or spending the time writing more unit tests. I am coming down more on the side of spending the time on testing, as I would like to see at least some unit tests in the code base.