Code Generation Tool

Having to write a lot of simple code once can be tedious and error prone – having to write it again for another language is even worse. Having to maintain both is just plain stupid. It would be quite handy to use a tool to generate all this basic code for us.

In my case I want the tool to create my standard code for my home automation software. I started with Java code but wanted to do an application in .NET and I didn’t want to port* or maintain both code bases – especially if the exact specification was still work-in-progress.

* Porting of the underlying base CDEF library was needed of course.

  • plain old data objects
    • fields can be
      • basic types (int, long, string) or other objects
      • lists of basic types or objects
  • messages
    • requests and responses
      • fields can be
        • basic types (int, long, string) or other objects
        • lists of basic types or other objects
      • encoding and decoding of data into byte buffers
  • languages
    • Java
    • .NET

The input to the tool is a form of specification defining all of the details and I chose to use XML to represent this data. Below is a very basic example of a simple class and message.

Running the tool and generating the code gives me the new source files. Note that the CdefMessage class is essentially a byte buffer. There is a constructor that pulls the data out of the message and an encode function to do the reverse.

In Java we get the same thing more or less. Ordering of encoding and decoding each field is important so we can send the objects between applications written in either language.

Here is the .NET Error message code, the Java is much the same. You can see how I handle lists of data objects and how they get encoded and decoded as required.

There are a few other helper classes that get created to make everything work but already we can create all this basic code with very little effort, no mistakes and knowing that both language libraries are in sync. This suits me as I’m very lazy and the less I have think about the better.

Leave a Reply