Send via SMS

Monday, April 17, 2006

Inversion

I want to talk briefly about a powerful language implementation technique, but I don't have any sample code for this one, because any sample code I provided would have all sorts of little fiddly bits which would distract from my main point. The technique is inversion, and it is increadibly powerful.

I could tell you that inversion is the process of turning a program into a tool, or that inversion is the act of re-writing a program to externalize it's game logic, or even that inversion is the process by which an API is wedded directly to a runtime environment, and the program is left for later. Maybe these descriptions are helpful, maybe they aren't, but they do set the stage.

Let's say that I've got a program which does something with, say, image files. That program is supported by a large API, and the API is supported by a complex environment which must be setup and torn down. So the program, roughly speaking, runs like this: first, it parses its arguments, and exits early if there is a problem (or help was asked for), then it sets up its environment, then it runs it core logic, a rather small program "written" in the language of the API, which actually does the work, then it tears everything down, and exits. If you want to add a new feature, you need to add a new bit to the API, or to the core logic, and sometimes to both. But as the API grows more powerful, more and more features are just additions to the core logic. And the core logic needs to be very general, because it can't be changed by the end user.

To invert such a program, we would stick a language interpreter in where the core logic currently resides (a big deal for compiled languages, but trivial for scripting languages). Then, interesting new applications of the API can be had by putting together a new little core program which runs in a language defined in terms of abstractions on the API, and that program can be very simple, because it need only handle its immediate application.