Do you create your own code generators?

In “Pragmatic Programmer” Hunt and Thomas distinguish between Passive and Active code generators.

Passive generators are run-once, after which you edit the result.

Active generators are run as often as desired, and you should never edit the result because it will be replaced.

IMO, the latter are much more valuable because they approach the DRY (don’t-repeat-yourself) principle.

If the input information to your program can be split into two parts, the part that changes seldom (A) (like metadata or a DSL), and the part that is different each time the program is run (B)(the live input), you can write a generator program that takes only A as input, and writes out an ad-hoc program that only takes B as input.
(Another name for this is partial evaluation.)

The generator program is simpler because it only has to wade through input A, not A and B. Also, it does not have to be fast because it is not run often, and it doesn’t have to care about memory leaks.

The ad-hoc program is faster because it’s not having to wade through input that is almost always the same (A). It is simpler because it only has to make decisions about input B, not A and B.

It’s a good idea for the generated ad-hoc program to be quite readable, so you can more easily find any errors in it. Once you get the errors removed from the generator, they are gone forever.

In one project I worked on, a team designed a complex database application with a design spec two inches thick and a lengthy implementation schedule, fraught with concerns about performance. By writing a code generator, two people did the job in three months, and the source code listings (in C) were about a half-inch thick, and the generated code was so fast as to not be an issue. The ad-hoc program was regenerated weekly, at trivial cost.

So active code generation, when you can use it, is a win-win. And, I think it’s no accident that this is exactly what compilers do.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)