Thursday, March 16, 2006

Code Generation: The Real Lesson of Rails 

Bill Venners
My observation is that the main technique Rails uses to improve developer productivity is code generation, even though Ruby's dynamic nature makes the code generation less obvious. The technique is also called metaprogramming, which simply means writing programs that write programs. Nevertheless, code generation is an old technique, and one I've used several times throughout my career to improve productivity.

. . .

However, to me what is important is simply that I'm expressing my intention in one place, and using a tool to generate other pieces of my system that can be determined from that one specification.

. . .

In my opinion, Rails applications feel like they require so much less code in great part because the generated code is hidden (but also because Ruby is concise in general). In our case at Artima, we see lots of generated .java files lying around in the midst of our project. On the other hand, we generate nice JavaDoc comments with our generated code, and so we get nice API documentation to look at if we want. If there's a problem or a question, we can go look at the generated code too. In Rails, it is just kind of magic. That makes it feel very lightweight, but if you ever encounter a problem with that magic, it might be more painful to solve it.

. . .

A database layer is often a good candidate for code generation, because these layers need to be updated whenever the database schema changes. If you only need to do something once, then writing a code generator is probably a bad idea. And even if you think you'll be doing this over and over, until you've done it several times by hand you probably don't know enough to automate. In our current architecture effort, we probably built about a dozen controllers by hand, and a dozen entities, before we felt we knew enough to automate.

I think programmers often don't like code generators that come from the outside, because like any framework they will often only take you 90% of the way you need to go. After that you start fighting the framework, which in a code generator often means you want to tweak the generated code. But that usually defeats the purpose of the code generator, which is to give you huge leverage. An exception are things like the scaffold generation in Rails, which is intended to just be a quick start that you edit and carry forward. Our in-house code generators are the kind where we aren't supposed to touch the generated code, and we solve the 90% problem because when we need to change the generated code, we change the code generator (since we wrote it, we can change it).

Topics: CodeGeneration | Programming | Design

Links to this post:


Comments: Post a Comment

This page is powered by Blogger. Isn't yours?