I’ve been working with myGeneration quite a bit lately as I prepare for my presentation at Edmug on the 24th of August. As part of the research I’ve been doing while creating the presentation material I’ve been working on creating a template for generating a data access layer in the format that I like. While doing this I’ve been trying to figure out how to best work with customizations to the generated code.
So far I’ve been looking at two different ways of handling custom code. The first is to use the preserve method provided by myGeneration and the second is to use a combination of abstract classes and the preserve function. Here are the arguments that I have been able to pin down so far.
Preserve only method
One of the biggest benefits that I see from this method is that all generated and customized code will reside in one location. This also has the drawback of making it less obvious, but not impossible, to determine where generated code ends and custom code begins. I also believe that this method can spawn the creation of a number of preservation blocks in each class (which myGeneration can handle quite easily) causing some unnecessary clutter.
Abstract classes and preserve method
Unlike the preserve only method, this way of separating generated code and custom code creates two locations of code for each class. The first location is an abstract class holding all of the generated code and never any custom code. Because this class is abstract we need to create a second public class that inherits from it so that we can use the generated structure. All this second class needs to do be is a shell class for the sake of inheritance. The body of this second class then becomes a preserve block so anything that is written in the class is preserved when the generator is re-run.
The benefit of doing this is that you have a complete separation between your custom code and your generated code. When you open one of the two classes you will immediately know whether you are seeing one type of code or the other. One of the best ways I’ve found to indicate this difference is in the use of namespacing and projects. For example you might have a separate name space and project for the abstract generated classes (i.e. MyCompany.MyProject.Data.Generated) and a second namespace and project for the concrete classes that inherit and extend the abstract classes (i.e. MyCompany.MyProject.Data).
My personal favourite of these is the abstract and preserve method. I like the distinct separation of the type of code. The main detractor in my mind is the need to have two classes for each business entity, but we can generate both of them, so it’s really not anymore work up front, just more code to maintain.