Strategies for Editing Generated Code

I’ve been working with C# and Java lately. The absence of metaclasses are sorely felt, because there are tonnes of boilerplate code which needs to be generated by the IDE to do any useful work.

Here are some of the strategies I’ve seen employed:

  • Netbeans uses protected sections, which prevents developers from accidentally modifying generated code
  • C# uses the idea of partial classes, which splits a class into (usually) two files – one which is generated, another which the developer is free to modify.
  • Ruby on Rails uses subclassing. The generated code forms the base class, leaving the developer free to edit a subclass.

I wonder how feasible it is the use automated 3 way merges to enable code base to be regenerated when the original template is revised. i.e.:

  1. Code generation tool generates MyExample.cs
  2. We hack on MyExample.cs
  3. We make some changes to the code generation templates and regenerate MyExample.cs
  4. We make a diff between #2 and #1, and apply that to #3. (we can use Meld library for python

This approach is nice in the way that we can edit the generated code, comment sections out, etc, and still retain those changes after code regeneration.

What do you think?