What is the best way to auto-generate values for features when an EObject is created?
I have some attributes in my EClasses I would like to initialize to a computed value when an instance is created. I'm wondering what the recommended way to do this using the framework is.
In one case I'd like to in开发者_如何学编程itialize the id attribute to a UUID. In this case I'd like the UUID value to be assigned when the object is first created and then remain the same for the life of the object.
In another case I'd like to generate a short id that only needs to be unique within the model instance.
I'm new to EMF and would greatly appreciate any guidance.
In both cases, I usually make the attributes suppress Setter
and initialize the them in the default constructor.
- the UUID is generated via
EcoreUtils.generateUUID()
- the class unique id is generated from a class static
nextID
The attributes are not made unchangeable
as we must (normally) be able to load a XML file and these must take precedence over the ones set in the constructors.
The class unique id, is slightly more difficult to handle as we must also initialize nextID
to a good value when the application starts.
Consider the sequence where we create a number of objects first and then load an old file: how do we ensure there are no duplicates between the objects? One possible method is to divide the id into two parts: a timestamp and a sequence number. Assuming we cannot restart the application within the resolution of the timestamp (usually one second) this works quites all right.
This solution still assumes we never need to load two or more old files as these may conflict if created at the same time in different application instances....
All-in-all, I normally stick with UUIDs as this method avoids all of the above problems :-)
精彩评论