DEV Community

Cover image for Fighting boilerplate with code generation
Ersin Buckley
Ersin Buckley

Posted on

Fighting boilerplate with code generation

Greetings fellow gophers.

Go is optimized for readability, but it can be a bit repetitive for the writing case. Adding features can require a lot of grunt work and boiler plate code.

Is boiler plate a problem?

Marshaling Responses

Marshaling responses from web services. If we are optimizing for readability, we should have strongly typed structs to marshal in to. This leads to grunt work in defining the type struct that maps to the web service. The code generation solution is using a tool like https://mholt.github.io/json-to-go/ .

Interacting with a SQL persistence layer

Getting your data in and out of a SQL database requires boilerplate.

  • Generating SQL DDL. Creating tables, indexes, relationships.
  • Row to struct scanning.
  • CRUD methods.
  • Complex Queries with type safe interactions.

There are a tone of tools in this place depending on the type of API you want to use with your crud methods, a couple worth evaluating are:

Building out an HTTP API

Taking your current data structures and operations and exposing them over an HTTP API can be rife with boilerplate.

  • Validating input
  • Generating consistent route structure
  • Marshaling and Unmarshaling data structures
  • Generating consistent query parameter interface (ordering, filtering, pagination)

Projects that help solve this:

Building clients for your service

Once you have exposed your web service you almost certainly want to consume it. Possibly you want to consume it over a number of different languages and environments. Thankfully, we can stand on the shoulders of giants here and use the open API IDL (Interface description langauge). The IDL will let you generate client libraries for numerous programming languages, and tools.

Check out everything you can codegen from the swagger IDL here https://swagger.io/tools/swagger-codegen/

T L D R

Go code is a pleasure to read, but can be a bit of a grind to write all that boiler plate. You can remove some of the grunt work through code generation. The design of Go has made it an easy tool for code generation. A mature ecosystem of tools makes it easy to get started.

Are you using code generation in your projects / day jobs and hacks?

Top comments (0)