Hate writing lots of repetitive boilerplate code?
Work with a large team and want to standardise/document common architectural patterns?
Want to get new developers up to speed quickly on best practices within your project?
YOU NEED CODE GENERATORS!!!
Code generators allow you to create code templates and folder structures for common tasks. For example in an Angular application, a code generator might have templates for creating components and services.
These are tasks that have to be carried out many many times in the implementation of a feature, and can be susceptible to different developers implementing them in different ways, resulting in time lost debating the best way to do things and/or confusion when reading other developers’ work.
With the addition of a generator, that has been agreed upon by the whole dev team, best practices within the project can be documented in the template, and another annoying decision/source of contention at the code review phase of a feature can be avoided. Hooray!
Generators can save a lot of time, and massively improve cohesion within a team. Obviously, as with anything, they can also make your life harder if they are not used properly.
If you use Angular, you may have used the Angular CLI (stands for Command Line Interface), which allows you to write things like
ng generate component my-component
inside a terminal in your project, and very rapidly have a skeleton
my-component component made for you, with code and file names in line with Angular best practices, complete with working tests.
Very cool stuff. If you write Angular code and you don’t use it currently, I would STRONGLY recommend giving it a try
Even if you do use the Angular CLI, what you might not know is that you can now write your own generators, using the same engine that the Angular CLI is written in, namely Angular Schematics.
Angular Schematics are fairly new, so the documentation is sparse and the API is a bit up in the air, but they are already quite nice to work with, with convenience methods for common Angular specific tasks, like adding module imports etc.
I personally have used them at work to streamline my team’s development experience when generating the vast amount of set up code that ngrx state management requires, and they have already saved a bunch of time and effort.
The schematics engine was designed with Angular in mind, but there is no reason you can’t use it to write generators for any code you feel like.
If these sound like things you might be interested in, then check out my schematics code here :