views:

30

answers:

1

Has anyone seen metamorphic code -- that is, code that generates and runs instructions (including IL and Java Bytecode, as well as native code) -- used to reduce boilerplate code?

Regardless of the application or language, typically one has some database code to get rows from the database and return a list of objects. Of course, there are countless ways of doing this based on your database connector. You might end up accessing the cells of the row by index (awkward, because changing "SELECT Name, Age" to "SELECT Age, Name" would break your code, plus the indexes obfuscate meaning), or using myObject.Age = resultRow.getValue("Age") (awkward, because this involves simply going through every field to set its data based on the columns).

Keeping with the database theme, LINQ to SQL is awesome. However, defining data models is less awesome, especially when your database has so many tables that SSMS can't list all of them in the object browser. Also, it's not the stored procedure writing or the SQL involvement that I dislike; just the connection of objects to database.

Someone at the company at which I intern wrote a really awesome method from our SqlCommand class (which inherits from the System one) that uses .NET reflection, with System.Reflection.Emit, to generate a method that would set fields (decorated with an attribute containing the name of the column) on any model object with a nullary constructor. I would consider this metamorphic because a specific part of the program writes new methods.

This pattern of generating objects from the database is just one example. One which I came across two days ago was databinding support for SWT (via JFace). I made these perfectly clean models with setAddress(Address address) and getName() and now I have to pollute the setters with PropertyChangeSupport fire-ers and carry around a PropertyChangeSupport instance (even if it is just in an abstract base class)! Then I found PojoBindables and now I feel like a level 80 databinder, simply because I need to write less.

Specifically, things that use native code with something like this or a Java Agent would be really sweet.

A: 

Generic programming might up your alley. The Concept C++ website has a really good tutorial that covers abstraction and lifting, ideas that can be used in any language and turn boilerplate code into a positive force. By examining a bunch of boilerplate methods that are almost exactly the same, you can derive a set of requirements that unite the code conceptually ("To make X happen you must do Y, so make X1 happen you must do Y with difference 1"). From there you can use a template to capture the commonalities, and use the template inputs to specify the differences. C# and Java have their own generics implementations at this point, so it might be worth checking out.

estanford