A rule by any other name
I call these "rules," but in many cases they can be only guidelines. Sometimes we have to break a rule because there really is no other way to achieve our goals. Nevertheless, the following rules were all learned the hard way, and should only be violated consciously.
An important bit of context for the following is that a Gradle build is divided into two primary phases: configuration and execution. Most of the rules are about what it is permissible to do in one phase or the other. Each phase carries with it different restrictions.
- Don’t do expensive computations in the configuration phase
It slows down the build. Such computations should be encapsulated in a task action.
- Avoid the
createmethod on Gradle’s container types
- Avoid the
allcallback on Gradle’s container types
- Don’t assume your plugin is applied after another
- Avoid making any ordering assumptions of any kind
Lazy configuration, callbacks, and provider chains are the name of the game.
- Don’t access a
Projectinstance inside a task action
It breaks the configuration cache, and will eventually be deprecated.
- Don’t access another project’s
This is called cross-project configuration and is extremely fragile. It creates implicit, nearly un-modelable dependencies between projects and can only lead to grief. Instead, share artifacts across projects by declaring dependencies. It also breaks the experimental project isolation feature, but that won’t be truly relevant for a while.
- Don’t call
Provideroutside a task action
- Don’t use internal APIs
Gradle considers internal APIs fair game for making breaking changes in even minor releases. Therefore, using such an API is inherently fragile and will lead to major, completely avoidable, headaches.
- Don’t use Kotlin lambdas in your public API
I know, it’s tempting. They’re right there. Use
Action<T>instead. Gradle enhances the bytecode at runtime to provide a nicer DSL experience for users of your plugin
- Don’t create objects yourself
ObjectFactoryinstead. (This is a configuration time concern.)
- Don’t use lists in your custom extensions
Use domain object containers instead. Once again, Gradle is able to provide enhanced DSL support this way.
- Don’t skip the documentation
I know, it’s a lot.
- Do test your plugins
Special thanks to Zac Sweers for offering feedback on this post.