samedi 27 décembre 2014

Auto generate unique IDs using the singleton pattern

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.


In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries. They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).


The given example:



class IDGenerator
{
private static IDGenerator instance;

private int nextID;

private IDGenerator() { nextID = 1; }

[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}

public int nextId()
{
return nextID++;
}
}


Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.


I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).


But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.


So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?


Aucun commentaire:

Enregistrer un commentaire