Code Generation Is Easy - With Picocog
Tags: java, meta, dsl, opensource
Published: 2018-01-08 13:47:18

---
title: Code Generation Is Easy - With Picocog
published: true
description: Meta-programming is, like, totally easy.
tags: #java #meta #dsl #opensource
---

[Picocog](https://github.com/ainslec/picocog) is a lightweight and new open-source Java library created to make programmatic code generation (or metaprogramming) clean, and easy to achieve.

Code generation is the process by which source code is programmatically generated based on inputs (also known as model).

Code generation typically works as follows:

* Define a model/use an existing model.
* Interrogate model and emit/generate source-code
* (Optionally) Upon changes to the model, regenerate source-code.

# Plain Old Java Objects

A code generator designed to leverage Picocog typically utilizes a POJO model as a source of model data.

Alternative use-cases are to use annotated Java source code, via the JSR-269 features of Java ([link](https://deors.wordpress.com/2011/10/08/annotation-processors/)).

For simplicity sake, this article will assume the PoJo scenario.

A sample POJO model is shown below (omitting getters/setters for brevity).


![Sample PoJo Model](https://thepracticaldev.s3.amazonaws.com/i/fopn6ml21s33vjjmaunc.png)


This POJO model is typically instantiated from the following types of sources:

* JSON/XML/YAML/CSV
* Via database query
* [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) (domain specific languages)

For example:


![XML representation of the model](https://thepracticaldev.s3.amazonaws.com/i/x4zdrn01ldkifizxna4b.png)


NOTE: It is important that the when instantiating the POJO model that a full set of validations are performed and assumptions tested. XML schema or a bespoke DSL implementation can ensure referential integrity and other validations.

# Code Generation

Picocog emits text via Java code. No templates, no reflection, no tag processing. It has three core goals:

* Generate cleanly indented code easily.
* Support out-of-sequence line injection.
* Be easy to debug.


# Picocog in Practice

Picocog can be thought of as a code-generation-centric alternative to StringBuilder.

Picocog simply writes lines — the current indentation level is remembered.

The only class that is required is the PicoWriter class.

There is no need to manually place indents into string literals, but there is a need to flag the indent left and write lines of code via the writeln_r(), writeln_l() and writeln_lr() methods.

Sometimes it is handy to want to write to two or more locations in a document simultaneously — and have those locations have their own indentation stack. To do this, you add a placeholder via the createDeferredWriter() method.

The returned writer can be thought of as a pointer to the line on which it was created.

# Sample Usage of Picocog
The code generation source code:
![The code generation source code](https://thepracticaldev.s3.amazonaws.com/i/dllnl00q0uflpb357ugg.png)


# Generated Classes

*Customer.java (generated by Picocog):*

![Customer.java](https://thepracticaldev.s3.amazonaws.com/i/kfcgwhgo76isdiijei9y.png)


*Order.java (generated by Picocog):*


![Order.java](https://thepracticaldev.s3.amazonaws.com/i/n97rdwhv345bb0p5n8rk.png)



# Escaping

The initial release of Picocog does not support any kind of textual escaping. Either write your own escaping code (quite easy) or leverage a library such [Commons Lang](https://commons.apache.org/proper/commons-lang/) for your [text escaping needs](https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html).

# Language Support

Picocog is written in Java, but it can **emit code in any language**.

A code generator can be created such that C#, Java, JavaScript, and more may be emitted from a single model, including annotations attached to Java code (via JSR 269).

Sometimes a small implementation is all you need.

# Links

Picocog is available today on [GitHub](https://github.com/ainslec/picocog).

Another non-template based approach for code generation is the excellent [xtend](https://www.eclipse.org/xtend/) language.

For a more in depth discussion of code generation, see the excellent article “[Code Generation For Dummies](http://www.methodsandtools.com/archive/archive.php?id=86)” by Matthew Fowler.

NOTE: This article is adapted (by the same author), from the following [blog post](https://medium.com/p/introducing-picocog-68de4978eaf4) on medium.com