Blog Stats
  • Posts - 6
  • Articles - 0
  • Comments - 0
  • Trackbacks - 15

 

Tuesday, July 05, 2005

Partial Classes & Code Gen

Carl Franklin wrote , amongst lots of other stuff, that Partial Classes may enable code gen.


I would argue that all we need for good code gen is inheritance, and that Partial Classes are an all-too-tempting red herring.


One of the basic problems with code generation has always been that, if you ever need to re-generate our code, you will wipe out any manual changes you have made to your generated classes. This is basically unacceptable, because the hand-written code is effectively the tricky bit (once you have the code gen working well that is). So, the trick is to find a way of protecting your hand written code, while keeping the benefits of generating code.


So, on the surface, partial classes seem very tempting. It can work in the same way that, say, the forms designer works in .net 2005. That creates a partial class for all the designer-generated gubbins, and a partial class for all your hand written bits. Neat! But there are problems. Eventually, you will need to alter the behaviour of one of your auto generated properties or methods with hand written code - and you won’t be able to do this. So then you have the dilemma - do you alter the generated code or not?


Using inheritance this need not be a problem. Your code generation should produce a set of abstract "base" classes. All base classes should be inherited by a "user" class - which ideally starts with no code in it. Any differences in behaviour can then be handled by overriding the base class member in the user class. You still have the benefit of preserving hand written code, but you gain the ability to generated behaviour.

Actually I'm very much looking forward to the next DNR. Kathleen Dollard is speaking and no doubt code generation will be a major topic. I'm sure she would be much more eloquent at  making the above point than me!

 

 

 

Copyright © Tim Ensor