Gradle files in modular projects
How to manage them like a boss!
If you are an Android developer, you should know this famous build.gradle file. It is essential for the project but may seem obscure at first glance and not everyone is happy when it comes to modifying it.
If you work on multi-module projects, you likely saw that there is one build.gradle file per module. We are then able to easily determine the developer’s pain formula:
totalPain = gradleFilePain * moduleCount
To simplify this, we are going to factorize our gradle files!
OK, let’s factorize! Where do we start?
Between your different modules, you surely have common libraries (UI component, DI, asynchronous work, …), and if you are a Padawan of Android / Gradle best practices, you probably already have a code block that contains the version numbers of these libraries (most likely in the project’s build.gradle file).
Here we will go further and centralize the major “groups” of libraries.
Let’s go from Padawan to Jedi together!
In my project, in every module that displays screens, I will need those libraries :
- appcompat
- fragment
- constraintlayout
As I don’t want to import this into all the gradle files of the affected modules, let’s factorize!
I create a libraries_ui.gradle file at the root of the project in which I write all my imports.
I just have to add an apply in the gradle file of each module to import all my libraries.
You can do this every time you feel it is necessary, with a different file for each import “group”, Gradle will merge the imports for you at compile-time!
Can we go further?
Factorizing libraries imports is great, but what if we go further?
In a multi-module project, we usually have an app module (the one that will be installed on the device) as well as several modules that will be used in app.
Most of the time, the content of the android gradle block is the same for every module. We will be able to factorize this part:
I decided to put this in a settings_core.gradle file at the root of the project and use it with an apply as seen earlier.
We can do the same for lint rules, signings configs, and so on…
Pushing the topic to the limit, I can easily end up with gradle files like this:
Now you can quickly create new business or UI modules with all the libraries and configuration you need, change lint rules for the entire project, migrate a library for the entire project, and much more. .. the only limit will be your imagination!
It’s your turn!
If you enjoy reading this article, please consider giving it a few 👏 👏 👏
Don’t miss our latest posts on Decathlon developer's website ✍ ️
Interested in joining Decathlon Tech Team? Check out our carriers portal 👩💻👨💻