Code generation: Poor man’s macros

June 19, 2021 – 100 days to offload countdown #88

I love macros. I would love to get paid to develop in rust or elixier, or in the best case some lisp dialect – that would be awesome. But I get paid to write, for the most part, php code.

Everybody and their dog loves to make fun of php developers, and every day stackoverflow is accepting questions tagged with php basically proves them right. I will gather some thoughts on why php as a programming language is better than its still rightly deserved public image some of these days. Having to write 100 posts in a short time frame can make someone desperate for things to write about.

In a language with real macros, which I see as code generation as first class citizen of a language, things that are orthogonal to the codes main purpose, like access control, caching, data sanity checks, can be expressed concisely with a single line of code that expands to the real deal, cutting down on boiler plate code and easing future enhancements and fixes immensely. In php we use the reflection API and comment tags to inform the generation of the final code (e.g. @cache TTL). Whenever possible using the language itself to create the final code is preferable to using an external tool like m4 or homegrown awk programs. php has anotations now, we will use these to replace doc-tags.

I once developed a j2ee based service, and without code generation this would have been a reason to quit the job – java as a language was so unsuitable to implment the j2ee concepts, 75% of the code written for a service was boilerplate code, if that would have to be written by hand, it would never have taken off.

Another range of problems suitable for code generation is data manipulation - seperate the filter and transformation logic from the code enables a devide and conquer approach and eases adaption of systems.