How to manage Gradle dependencies in an Android project properly.

Dmitriy Voronov
Doubletapp
Published in
8 min readApr 24, 2020

--

Introduction

If you’re reading this article, you probably did at least one android project. It means you’re familiar with the Gradle build system, and pain that comes up with management Groovy files. What if I say that you can minimize this pain a lot? Moreover, you can do this with Kotlin ❤️.
Gradle dependency management can be done in at least three various ways. Let’s review each of them in detail.

Summary

  • Plain dependency management;
  • Dependency management via ext;
  • The right way;
  • Managing repos;
  • Keeping dependencies up to date;
  • A few words about Kotlin DSL.

Why should I even care?

As soon as your project will grow, the count of its dependencies rise, and build.gradle files will become such a mess and error-prone. As soon as you will modularize your project, you will get many build.gradle files with the same content and will have to manage each file manually.

1) Plain dependency management ❌

The worst approach you can manage your Gradle dependencies is to perform no special workaround and use plain strings alike:

Plain dependency management with strings

Everybody managed dependencies this way at least once, but it requires a lot of manual changes whenever you upgrade your libraries. Keep in mind that many dependencies are come from one group and have the same version. Moreover, the project may include more than one module, and you'll have to update dependencies in other modules too (look at the samples below).

build.gradle in the module 1
build.gradle in the module 2

As you can see, it has a lot of boilerplate code which can be reduced. It would be great to put these dependencies and their versions in variables and all of them in one place. Let’s see what we can do.

Pros:

  • None… Except for the case, when you’re making a very simple project — you’ll save a little time.

Cons:

  • Your build.gradle files become messy when the project grows;
  • In multi-module projects, you have to update the dependencies manually for each module;
  • Strings are “dangerous” and error-prone.

2) Dependency management using ExtraPropertiesExtension (ext) 🆗

Another very popular method is to keep your dependencies in ext. This method is OK. Furthermore, it’s recommended by Google. Despite this, I wouldn’t recommend using this method and let’s see why.

The core of this method is to keep all of the dependencies and their versions in one place — ext object by key/value pairs.

What is ext?

From Gradle docs: Extra properties extensions allow new properties to be added to existing domain objects. They act like maps, allowing the storage of arbitrary key/value pairs. All ExtensionAware Gradle domain objects intrinsically have an extension named “ext” of this type.

For example, you can create ‘deps.gradle’ (or any other name by your choice) file in the project’s root folder. And its content will look something like that:

deps.gradle file in project’s root folder

As you can see, dependencies and their versions are stored in a Groovy map by key/value pairs. Versions are taken out, cause different dependencies from one package/group have the same version number. And we all like to reuse the code, don’t we? 😎

Then you can apply these dependencies whenever you need by specifying “apply from: ‘[name].gradle’” in necessary buildscript (top-level in our case):

Applying all from the ‘deps.gradle’ file in the top level ‘build.gradle’ file

And using these dependencies in action looks like this:

You are supposed to notice a lack of autocomplete, navigation and highlight. It becomes a game-changer for me, so I decided to dig deeper and discovered the third method — buildSrc.

Pros:

  • All of your dependencies are stored in one place;
  • Build.gradle files look neat.

Cons:

  • Lack of the highlight, autocomplete or navigation;
  • IDE will not show you a warning if dependency is out of date;
  • You’re still using error-prone strings, as you get the dependency by string key from ext, and you never know you’re using the right key till building the project, because of lack of the IDE highlight.

3) Dependency management using buildSrc ✅

As Madis Pink wittily noticed in ZeroTurnaround RebelLabs blog about what buildSrc is: If somebody asked about the Gradle feature that everybody should know about, I would probably point them towards buildSrc. It is a magic Gradle Java/Groovy project inside your repository, available as a library to all of your build.gradlefiles.

It allows you to write custom build logic (declare dependencies, writing tasks, and plugins, etc) using your lovely Kotlin🤘, so stop wasting time and let’s go!

First, you need to create a folder named ‘buildSrc’ in the root folder of your project:

$ mkdir buildSrc

Then, to be able to write Java/Kotlin code you have to create a default for java projects src/main/java structure inside just created folder:

$ mkdir -p buildSrc/src/main/java

Last preparation step: create build.gradle.kts file to enable kotlin support in Gradle.

build.gradle.kts file inside buildSrs dir

Now you just need to create a kotlin file inside a newly created folder and move all of your dependencies and versions inside. This way you’ll get full code completion, highlight and navigation support right in the IDE! Here’s a very simple example:

And now we can reference these in our build.gradlefiles:

At first glance it may feel wrong to put build configuration inside the buildSrc module, though the benefits are still worth it.

Pros:

  • All of your dependencies are stored in one place;
  • Build.gradle files look neat;
  • You get full of the IDE highlight, autocompletion, and navigation.

Cons:

  • IDE will not show you a warning if dependency is out of date;

4) Keep your dependencies up to date

As you can see, the big downside of both ext and buildSrc methods is IDE will not show you a warning if dependency is out of date, so let’s turn it into a significant advantage.

Default newer version check

By default, IDE checks for the newer version by the ‘Newer Library Version Available’ lint inspection:

It isn’t compatible with both ext and buildSrc methods but nothing to worry about as it’s far from ideal. Sometimes it works a bit incorrect and doesn’t warn some outdated dependencies:

Incorrect ‘Newer library versions available’ inspection work

After a very short research, I decided to use the Gradle Versions Plugin developed by Ben Manes.

Gradle Versions Plugin

It’s more stable than Lint inspection and can be configured to match all of your needs. I will not focus on how to add this plugin to the project, its GitHub page has an exhaustive instruction.

To make the magic happen you need to run dependencyUpdates task by prompting this command in terminal:

$ ./gradlew dependencyUpdates

And task’s default output looks like this:

The following dependencies have later milestone versions:
- androidx.appcompat:appcompat [1.0.0 -> 1.2.0-beta01]
https://developer.android.com/jetpack/androidx
- androidx.constraintlayout:constraintlayout [1.1.0 -> 2.0.0-beta4]
http://tools.android.com
- androidx.core:core-ktx [1.1.0 -> 1.3.0-rc01]
https://developer.android.com/jetpack/androidx
- androidx.test.espresso:espresso-core [3.1.0 -> 3.3.0-alpha05]
https://developer.android.com/testing
Gradle release-candidate updates:
- Gradle: [5.6.4 -> 6.3 -> 6.4-rc-1]

As you see, it suggests updating the dependencies to beta, alpha, and RC versions. To make it focus on release versions only — some task configuration is needed.

Just add this function to your ‘Dependencies.kt’ file:

And place this code to the bottom of the top-level build.gradle file:

Just put it in top-level build.gradle file

That’s it! It suggests release versions only now:

The following dependencies have later milestone versions:
- androidx.appcompat:appcompat [1.0.0 -> 1.1.0]
https://developer.android.com/jetpack/androidx
- androidx.constraintlayout:constraintlayout [1.1.0 -> 1.1.3]
http://tools.android.com
- androidx.core:core-ktx [1.1.0 -> 1.2.0]
https://developer.android.com/jetpack/androidx
- androidx.test.espresso:espresso-core [3.1.0 -> 3.2.0]
https://developer.android.com/testing
Gradle current updates:
- Gradle: [5.6.4 -> 6.3]

If you want some fine-tuning, check the GitHub page. You can even configure the task to save its report in the file and use this file with Danger in your CI/CD pipelines to warn you about newer versions automatically.

5) (Bonus) Managing the repositories alongside dependencies

If you read up to this point, I’d like to share with you one of the ways to manage your repositories alongside dependencies. It could be done by gradle interface — RepositoryHandler.

From Gradle docs: A RepositoryHandler manages a set of repositories, allowing repositories to be defined and queried.

Doesn’t matter what method you use, whether ext or buildSrc, you can do that trick with both. All you need is to create a method that receives RepositoryHandler as a parameter like this:

Dependencies.kt file inside buildSrc folder
deps.gradle file with ext

Then just call it inside the build.gradle file and pass the ‘repositories’ handler inside:

Apply the repositories by calling the addRepos() method

Now you can keep all of your build configurations in the same place, which made its management as simple as never before. And how do you manage the repos? Write in the comments below.

6) Kotlin DSL

You may notice, Kotlin DSL used in the buildSrc module. It’s needed to support Kotlin code inside. It’s natural to use it in some modules but not to use it in the entire project. If you’re a Kotlin fan like me, I have to suggest that you at least try Kotlin as the main Gradle language.

From Gradle Kotlin DSL samples at GitHub: The Gradle Kotlin DSL provides support for writing Gradle build scripts using JetBrains’ Kotlin language. It aims to provide Gradle users with a rich, flexible and statically-typed approach to developing build logic in conjunction with the best IDE and tooling experience possible.

So, Kotlin DSL gives you an ability to write your Gradle files, tasks, and so on in Kotlin. It makes Gradle files much more readable and simple. But it isn’t fully supported yet and has a build speed issue at first build with cold Gradle daemon. But Kotlin DSL has official support by the Gradle team, and they teamwise with the JetBrains do their best to make it better.

Conclusion

I’ve described all the methods I know, please, tell me how you’re managing dependencies in your project. Also, I would appreciate, if you let me know how you’d like the story, it’s my first attempt at writing. Feel free to use comments below or ping me on social media. Thank you for your attention.

Sample project

Related Links

Share post, hit the Clap button!

This material has been prepared by Doubletapp — High Tech IT Solutions Development Studio.

Reach us at hi@doubletapp.ai. We will bring your ideas into real life.

Contacts

Doubletapp site doubletapp.ai

Facebook | Dribbble | Instagram | Twitter | Telegram

--

--

Dmitriy Voronov
Doubletapp

I’m an Android Developer living in Saint-Petersburg, Russia. Currently working at Doubletapp.ai.