Code Generation 🧬

Benefits

Code generation can be used to automatically create models, objects, and templates from a defined specification. Some benefits:

  • Reduce Human Errors - Code created by generators will be consistent and avoid common mistakes that can occur with manual coding.

  • Save Time - Not having to manually write repetitive code for models/objects saves significant development time.

  • Consistency - Code generators create uniform code following consistent styles and patterns.

  • Validation - Generating code from a validated spec or schema ensures the output adheres to the defined contract.

  • Focus on Core Logic - Developers can spend time on the application logic rather than repetitive modeling tasks.

  • DRY Principle - Auto-generated models prevent duplication of schema definitions in multiple places.

  • Easy Maintenance - When specs change, code can be regenerated quickly rather than refactoring manually.

Examples

Code generation exists in many shapes:

Mustache (OpenAPI)

{{#models}}
public class {{name}} {
 
  {{#fields}}
    {{^isContainer}}
    {{#required}}
      @NotNull
    {{/required}}
    private {{type}} {{name}};
 
    {{^required}}
    public Optional<{{type}}> get{{name}}() {
      return Optional.ofNullable({{name}});
    }
    {{/required}}
    {{/isContainer}}
  {{/fields}}
}
{{/models}}

This generates a class for each model based on the fields.

Velocity (Avro)

#foreach($avro in $avroModels)
{
  "type": "record",
  "name": "$avro.name",
  "fields": [
    #foreach($field in $avro.fields)
    {
      "name": "$field.name",
      "type": "$field.type"
    }
    #end
  ]
}
#end

Similarly, this generates a class per model by looping through models and fields.