My stack is intentionally simple. I use Go for backend APIs, MongoDB for my datastore and Angular for the frontend layer. Despite this, I still find that it takes longer than I’d like to go from:
Have an insight
Form a hypothesis
Explore validate metrics
Build something
Test it with customers
Revisit the hypothesis.
I’m constantly in pursuit of ways to sustainably reduce my lead time (the overall time between steps 1 and 6).
Enter Go generics
With Go generics, I’m able to purposefully refactor. Abstracting away boilerplate code that represents so much “toil”.
Shown below is the typical mongoDB boilerplate code for Retrieve actions.
With Go generics, I can simplify this to several fewer lines of code. Now all of the messy bits is abstracted away in a generic function call:
_getAccountItems[T any](…) ([]T, error)
.
This is a go first step. However, I still have to write the same CRUD (Create, Retrieve, Update & Delete) abstractions for my each model.
For instance:
Faster still with Go generators
In the last 3 examples above, I was interacting with data that related to the following model.
For this Model, I need to do CRUD operations. With go generators, I can annotate the models with go:generate model-api-builder
and use vs-code (or a CI pipleline) to generate that code form.
In the example, I create model-api-builder so that when I specify the Model, and the MongoDB collection and all the related code is generated.
Similarly, I can feed it additional options (e.g. -nogen=delete,list) to exclude some db options.
This simple quality of life helps to improve not only the speed at which I work, but it also helps me to write cleaner code with fewer bugs.
Happy coding!
H