Generating code is the smart way

Generating code is the smart way

I spend much of my day coding away furiously, mostly in Codeigniter (PHP, Javascript, jQuery & MySQL). The usual open source stuff.

field definitions

Most CRUD (create, read, update & delete) operations follows the same pattern of code.

There is a controller that drives the main functions, a list view (using the awesome datatables plugin) to show a table of data and a edit popup screen to create or modify the record. Then there is a delete and optional enable/disable function, together with maybe some additional tabs on the edit screen.

How hard can it be to combine all this into a code generator?

Actually not too hard it turns out, but then you add all the bells & whistles that gives your application an edge. Stuff like smart validation, typeahead, event selectors, image unloaders, auditing & permissioning, etc.

So suddenly what was a simple starting point turns into a big destination. Several hours later (ok, many hours later) I have a working code generator. Now I need a simple front-end to define the parameters for the generator to use. Oh, and then I need to add a bit of code that actually generates the database migration code as well.

It all worked out in the end, and straight forward CRUD type stuff are now being generated in mere moments. As I need more complex components like a google maps based field or a colour picker I add these into the code generator, so I do not need to manually amend the code. Once you touch the code by hand you are at the point of no return. No longer can you simply add a new column or re-arrange the order of the columns by just editing the definition and re-generating, but you are forever stuck with manual editing going forward. Such a primitive concept.

The generated code is now the new standard for our company. It is the measuring staff for all hand written code. It defines the way we do comment our code, the way crud auditing is done , the way permissions are controlled, etc. We now have a consistent approach to coding, and it makes code reviews much easier.

So, generating code the lazy way actually makes your life much simpler in more ways than you would think. Not only do you code faster, you also code better, you review more consistently, which means less bugs, which has its own round of spin off benefits.

Sadly, before you ask, no, my code generator is not open source, as it contains lots of secret sauce that gives us a real edge.

Leave a Reply