Skip to Content
Tech PrinciplesTechnical ResourcesApplicationCode Generation

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.

Future

Ways AI could enhance code generation:

  • Automatic template creation - AI could analyze requirements and automatically create optimal templates for code generation.

  • Adaptive templating - AI could monitor outputs and continually refine templates to produce higher quality code without human intervention.

  • Context-based generation - AI could understand context like app purpose and team preferences to customize generated code.

  • Expanded capabilities - AI could generate not just models but complex application logic and behaviors tailored to the use case.

  • Maintenance - AI could automatically update templates and regenerate code as requirements change.

So in the future, AI may play both roles - replacing hand-coded implementations as well as automatically handling template and generator creation.

Last updated on