Attention: We are retiring the ASP.NET Community Blogs. Learn more >

The problem with code generators

It's quite usual to hear "the problem with code generators is that if you change the code they generate, you lose the changes the next time you generate the code".

I would say "the problem with code generator users is that they want to change the generated code" ;).

Code generators that let you modify the generated code and keep the changes the next time you regenerate are usually quite fragile. This is the best example:

#region Windows Form Designer generated code
/// <summary>
  /// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300,300);
this.Text = "Form1";
}
#endregion

We all know what happens when you start messing up with the code inside InitializeComponent() ;)

But there is a more important reason for not to change the generated code. What happens if I want to refactor my code generator to take advantage of new features of the framework (i.e. Generics)? It will be impossible to keep the changes, so we lose one of the big advantages of code generation that is being able to completely change the way it generates code in the future.

There are a couple of ways to change the behavior of a code generator without changing the code. The best one is to improve the code generator metadata, so it generates the code you want. The other option is to use composition or inheritance to modify the behavior of the generated class. This last one adds more coupling to the generated code than the first one, but as it's using the public signature of the generated component, it's pretty safe.

No Comments