-
Notifications
You must be signed in to change notification settings - Fork 161
Home
What are some use-cases when jennifer would be useful?
Hi, good question!
I think any sufficiently complex code generation task would benefit from using jennifer. A simpler job will always be easier using templates, but as the complexity increases, this package will make more sense.
Here's a couple of problems I came up against when using templates for code generation:
-
In the "imports" section... Did I use the
foo
package? The only call tofoo.Bar
might be conditional on some complex logic... It might be conditional in two separate places, with different logic! All that logic will need to somehow be in the imports section too or you'll end up with unused or missing imports. -
A problem I came up against in the kego project was that the system package:
kego.io/system
has lots of functionality I use in the generated output. So I'm calling functions likesystem.Foo()
. However, the generated output file has to support being local to thekego.io/system
package - in which case the syntax of the function call would simply beFoo()
. In templates, you end up with something like{{ if localPackage ne "kego.io/system" }}system.{{ end }}Foo()
, which isn't ideal.
If you're starting a code generation project, I'd recommend you have a go with text templates first, and take a look at jennifer if you start to come across problems.
Take a look at the genjen package as a perfect real-world example. Many of the methods and functions in jennifer are simple boilerplate, so a perfect application of code generation. The genjen package uses the data in data.go, processes it with the render function in render.go and outputs the generated.go file in the jen package.