Last night I was working on something and suddenly found myself needing about 30 really simple ActiveRecord classes. I figured it was about time to stop writing these manually each time.

Looking at the CastleProject.org site, and seeing that the status of ActiveRecordGenerator was frozen, I briefly considered writing my own little tool (or just modifying ActiveRecordGenerator as needed) to do the job. After another 10 minutes, I finally broke down and made a CodeSmith template (we've got CodeSmith, but for some subconscious reason I keep avoiding using it.)

This was fairly straightforward, and after 20 minutes or so, I had the template I wanted, and started generating classes. After another 20 minutes I had added some things I missed the first time and everything was great.

After completing this, I looked at what I had done, and found myself thinking: this is alot of cruft.

Let me mention that all 30 classes had basically the same set of properties. I briefly considered writing a generic class, but didn't think there would be a way to get the name of the class into the '[ActiveRecord("MyTableNameIs")]' attribute. That, and a small handful of special rules, were the only things different about these classes.

I was thinking: A lisp-like macro would have been really useful. Why don't we have lisp macros in OO languages like C#? I've always fealt (but not agreed) that it's because OO leads you to composition instead of code generation. I could have written one base class with the properties I wanted, then 30 derived classes with the right names and attributes. That is still too much typing, though, and I would have used code generation anyway. I chose not to relate these classes, as they are not really related in this domain anyway, only functionally and structurally related.

I am not sure what the best answer to this type of design problem is, but I know I haven't found it. Code Generation is a jack-hammer in the face of the problem of code duplication caused by imperfect design. It gets me through the barriers, but the barriers were trying to tell me something.

Frameworks and tools (like ActiveRecordGenerator, or even better - Streamlined) that generate applications based on meta data are becoming very popular. Are these tools just reactions to the lack of good DSL tools or lisp-macro-like facilities - i.e., why am I writing my C# application in Code Smith templates and not in C#?


 
Comments are closed.