in reply to Code that writes code
I have done this, and recommend it with warnings. The
main problem is that you are creating a layer of indirection
between you and the problem. This makes it harder to figure
how how you should do the problem. But when you get the
solution, the solutions tend to be better.
There are many basic approaches that I have used. Each has advantages and disadvantages.
- You can write a little macro language which is turned into code and evalled. Damian Conway is fond of this approach. See for a random example, Class::Contract. Generally this takes a lot of work to do, and involves creating a macro language. But the result can be very powerful. (Usually I just use some subset of Perl as my macro language and use do or eval to parse and interpret it...hrm...)
- You may have boiler-plate code to insert in appropriate places. See, for instance, AbstractClass. Outside of very rigid problems, this approach makes symbolic references look downright sane.
- Your use of text manipulations to make code in one form turn into another is common. Particularly for mass edits, obfuscating code, so on and so forth.
- Turning data structures into code and back is often very useful. See Data::Dumper. (I have used similar techniques to freeze data structures in one language and re-instantiate them in another.)
- Often a large and complex script can be maintained as an auto-generated thing from a number of small ones through some sort of template. Perl's Configure shell script is maintained this way. Take a look at the make utility for some ideas on how to do that.
Hopefully this should give you some ideas for how to use automatic code generation, and a few places to look for examples of it being done.. :-)
In Section
Meditations