Reality-Loop

Code Generation vs. Code Synthesis

October 09, 2007 | 1 Minute Read
This post was originally posted on my old blog.

In one of the latest DNR-Interviews Venkat Subramanium makes an interesting statement:

I think code-generation is so 20th century! What you want is code-synthesis.

With code-synthesis a method is actually generated in memory on the fly, it is never created on the disk for you to mess with.

With code generation, the minute you generate the code, its like an itch in the back. You want to modify it, you want to scratch it a little bit and then it turns into a sore after a while.

-Venkat Subramanium, DNR 277 [36min 30s]

 

I think the distinction between code-generation and code-synthesis is very fluent. The C# compiler is basically just a code-generator (it generates IL-code). ASP.Net is also a code generator that generates IL from ASPX-pages (and code-behind).

image In the case of ASP.Net I personally would also talk about code-synthesis, because the generation process is almost completely hidden from the developer and also happens (almost) at run-time and not at compile-time.

This is in contrast to classical code-generation that is promoted by MDA or tools like CodeSmith and MyGeneration ...

Traditional static languages lend themselves to code-generation. Code-synthesis on the fly is a rather complicated endeavor (who does really understand how ASP.Net works under the hood?).

Modern dynamic languages like Ruby or Groovy are much better qualified for code-synthesis. Since they are interpreted, there is a much more powerful runtime to begin with. Furthermore they offer powerful metaprogramming capabilities. This makes dynamic runtime-behavior much more feasible, which in turn is the base for creating DSLs or code-synthesis.

Just to exemplify the consequences of the differences between code-generation and code-synthesis:

Look at the following ActiveRecord model:

 class Firm < ActiveRecord::Base
   has_many   :clients
   has_one    :account
   belongs_to :conglomorate
 end

And now think about all the lines code that get generated, if you want to realize the same model with a strongly typed DataSet...