james mckay dot net
because there are few things that are less logical than business logic

On code generation

A lot of developers love code generation. Some pretty smart ones hate it. The following is my observation on the matter.

Code generation done right can save masses of time. Code generation done wrong has the exact opposite effect.

Here is what code generation done wrong looks like. I am asked to help out with your project, and told that it’s corrupting data. After a bit of rootling around, I find two hundred business service classes, each containing numerous very similar looking methods that all follow this pattern:

public bool SaveWidget(Widget widget) {
    try {
        return true;
    catch (Exception) {
        return false;

Pffft. Pokémon exception handling all over the place. No wonder it’s corrupting data.

If you’d left your templates in your solution, with a comment explaining where to find them, I could get rid of Pikachu and Bulbasaur and friends in five minutes. But since you didn’t, I have the thankless task of spending the rest of the week going through the whole lot by hand.

Here’s how to do code generation right:

  1. Do include a header at the top of each autogenerated file, indicating (a) that it has been autogenerated, and (b) what it was autogenerated by.
  2. Do include your template files and/or scripts in source control.
  3. Do re-generate your autogenerated files as part of your build process, before running your unit tests.
  4. Don’t edit autogenerated files manually. Use partial classes and partial methods instead.

By following these four simple rules, you can ensure that if someone comes to your project at a later date and finds that there is a fundamental flaw in your generated code, they can easily fix it.

1 trackback:

1 comment:

  • # Reply from Glen Smith at 16:00 on 22 Sep 2010

    I am sure you would agree that frameworks have the same effect if done badly.

    A “framework” which translates a copy of a monolithic collection of tightly coupled objects as wrappers to perfectly good third part tools and code (which would be better suited as services) does not only breaking every convension in the book, it binds you to a single version of your development platform and tools; and reduces your time to market as all developers will need extensive training on the system. There is also the possibility of introducing a huge licencing overhead with some third party tools.

    Code reuse through code generation/ regeneration is a huge misunderstanding of the term. Code reuse is write once, use many. This is not to be translated as copying to each class.

    Take a look at this take on the subject…


Comments are closed.