EMF Dos and Don´ts #4

March 13, 2013 | 2 min Read

EMF is a very powerful framework and with power comes…responsibility. You can achieve great things with a minimum of effort using EMF, but if something goes wrong, you can also spend hours trying to find out why. This blog post is part of a series on things you should do and things you should not do when using EMF. You can use the link to the series pilot to navigate to the start and the next link below to navigate to the next blog once it is published.

EMF Don’ts #4: Default initialization in EMF Factories

For every package in an Ecore file, EMF will generate a Factory class, which allows you to create an instance of all defined EClasses in the respective package. The factory method of a specific EClass might seem like the correct place to implement a default initialization, but it is not. The factory is used by other framework classes to reflectively create instances of a model. These classes include XMLResource, which uses the factory to create the object during de-serialization, and EcoreUtil.copy(), which uses the factory to copy an EObject. If you add a default initialization to the factory code, this code will likely cause problems such as changing an object during de-serialization from XML. The problem is related to my previous blog post on changing generated getters and setters.

Default initialization is either a matter of defining default values for primitive data types in your Ecore model or of controller code in your edit or editor plugins. Good targets for implementing such code are the ItemProviders of an EClass if you use them to create new instances of EObjects. The ItemProviders expose the method collectNewChildDescriptors() to define the containment children that can be overridden to add some default initialization. Furthermore, using ItemProviders has the advantage of providing more context on how to do the initialization since you will know the parent object and its resource potentially. If you are not using the generated editor or the provided Descriptors for creating EObjects, you should still put the initialization code in your controllers, not in the factory.

Stay tuned for more Dos and Don´ts in my next blog!

Jonas, Maximilian and Philip

Jonas, Maximilian and Philip

Jonas Helming, Maximilian Koegel and Philip Langer co-lead EclipseSource. They work as consultants and software engineers for building …