Editorials

Templates Rock

There have been a few responses to the Code Generation editorial from the 17th of june. Most have emphasized the benefits of code generation as being useful. There were a few pitfalls, however.

  • Developers were not maintaining their understanding of the layers of code that were automatically generated
  • Custom modifications to the code were lost when classes were re-generated
  • Sometimes the code generator tied you into a specific product

There were a lot of good things to be said about using code generation. For example, one company used T4 templates to generate a data access layer working in VB6 and later in Dot Net. The time to make the adjustment to new code was extremely fast.

I have seen templates used to change the storage engine instead of the platform. An application written to use MongoDB was transformed to use SQL Server in a matter of a few hours. This works well in a Domain Driven model.

The thing I like about T4 templates is that you can create your own, modify templates from others, or use canned templates. You are not restricted to a specific set of templates if you are willing to learn the syntax to write them. For example, I used NetTiers templates before T4 templates were available. Using the templates I was able to add a logging feature to track all data changes. Think about how often you have had to do something like that, and the amount of time it took for each table to be audited.

Another technique to retain your customizations of generated code is to use partial classes. The generated code is in one file, and your customizations are in another file. When generation occurs, only the generated file is re-written. The compiler pulls the two different code files together as a single code object. As long as the generated code doesn’t conflict with assumptions in your custom code file, you continue to move forward without losing your user defined code extensions.

Thanks everyone for your contributions.

How have you made templates work for you? Do you customize them or use ones developed by others? Do you use partial classes? Share your thoughts online or send an Email to btaylor@sswug.org.

Cheers,

Ben