Integrating detekt in the Workflow

Learn how to integrate the powerful detekt tool in Android app development to help detect and prevent code smells during the development process. By Harun Wangereka.

Leave a rating/review
Download materials
Save for later
Share

There are several ways to keep your technical debt low throughout the development process. Finding potential problems early — and minimizing them — is important. It’s also a good idea to maintain your team’s code styles and conventions and keep the cognitive complexity of methods within acceptable limits.

detekt, a static code analysis tool for Kotlin, helps you do all of this. It comes with a wide range of rule sets. It provides you with options to configure them, as well as the ability to add your own custom rules. So, adding this as a part of your CI steps can prove to be beneficial. CI stands for Continuous Integration, a process of ensuring features and bug fixes are added to an application regularly.

In this tutorial, you’ll build DetektSampleApp, an app that shows detekt rule sets with their details. During the process you’ll learn about:

  • detekt and its features.
  • Adding detekt to your project.
  • Rule sets available in detekt.
  • Writing custom rules and processors.
  • Integrating detekt into your IDE.
  • Adding detekt to GitHub Actions.

Getting Started

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

Open Android Studio 4.2.1 or later and import the starter project. Then, build and run the project. You’ll see the following screen:

detekt Rule Sets

The app shows a list of detekt rule sets. Each rule set has a short description of what it does. Clicking on any of the rule sets takes you to a view that loads the official documentation from the detekt website.

detekt Rule Set Explanation

Understanding detekt

detekt is a static analysis tool for the Kotlin programming language. It tries to improve your codebase by enforcing a set of rules. You can integrate it with your CI to help avoid code smells on your codebase. This is helpful — especially when working with a team of developers.

detekt has several features that make it a worthwhile addition to your project:

  • It offers code-smell analysis for Kotlin projects.
  • It’s highly configurable — you can customize it according to your own needs.
  • You can suppress findings if you don’t want warnings for everything.
  • IDE, SonarQube and GitHub Actions integration.
  • You can specify code-smells threshold to break your builds or print warnings.
  • You can add code-smell baseline and suppression for legacy projects.

You’ll learn about all of these features in this tutorial. Now, it’s time to add detekt to your project.

Adding detekt To Your Project

You can easily add detekt to new or existing Kotlin projects. For existing projects, you’ll add some more customization to prevent many errors.

Adding to New Projects

detekt is available as a Gradle plugin. For new projects, add the plugin via the Gradle files.

Navigate to the project-level build.gradle file. Add the corresponding classpath in the dependencies block:

classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.17.1"

Here, you define the path that Gradle will use to fetch the plugin.

Next, you need to add the plugin to your project.

Below the dependencies block add this:

apply plugin: "io.gitlab.arturbosch.detekt"

With this, you apply the detekt plugin to your project. The final step of adding the plugin is to apply the plugin on the app level Gradle file.

Navigate to the app-level build.gradle file. Add this apply line:

apply plugin: "io.gitlab.arturbosch.detekt"

This enables you to use the plugin in the app module too. With this added, do a Gradle sync. After the sync is complete, your plugin is set and ready to use!

Note: detekt requires Gradle 6.1 or higher. You can check the supported version from the compatibility documentation.

Running detekt Terminal Command

Now that you have the detekt plugin set up, run the following command on your terminal:

./gradlew detekt

Once the task completes, the build will fail with the following results:

Detet

There are a few things to notice:

  • At the very top, detekt shows warnings from Gradle. Currently, it shows a deprecation warning.
  • You can see the red text with the message Task :app:detekt FAILED. Below this text is a list of detekt rule sets. In this case, you have naming and style rule sets. In each rule set, you can see the rule that has been violated and the file together with the line. This makes it easier for you to pinpoint where in your code you need to do refactoring. Each rule set has an associated debt.
  • After the rule sets, you have the Overall debt: 1h 25min text. detekt estimates the total time it would take to fix all the code smells in your project. Imagine this is a new project and you already have 1 hour and 25 minutes of debt. And if it were an existing project, you could have days and days of debt. That’s a code smell already!

Congratulations! You’ve set up detekt in your new project successfully. Quite easy, right? :]

Now, you’ll focus on learning how to add it to an ongoing project.

Adding to Existing Projects

Integrating detekt into an ongoing project can result in many warnings and violated rules. The debt can be a lot of hours that you may not have time to resolve.

One option is to ignore the legacy code and instead focus on the code you add after integrating detekt. To do this, detekt allows you to define a baseline property that generates a list of every violated rule that detekt will ignore. Run ./gradlew detektBaseline, and this generates a baseline file for you. Now, when running ./gradlew detekt, detekt will ignore warnings listed in the baseline file. Check out the official documentation to learn more about baseline configuration.

Note: You can remove this baseline whenever you want, and you’ll see all the warnings again. To do so, remove the app/detekt-baseline.xml generated file.

In the next section, you’ll dive deeper into the detekt rule sets to know what they are. You’ll also look at rules in the rule sets.

Looking at detekt Rule Sets

The DetektSampleApp already includes a list of the rule sets and their descriptions. Rule sets contain a group of rules that check compliance with your code to improve the code quality. The rules don’t affect the functionality of your app. Here are the common rule sets that exist:

  1. Comments: It provides rules that address issues in comments and documentation of the code. It checks header files, comments on private methods and undocumented classes, properties or methods.
  2. Complexity: This set contains rules that report complex code. It checks for complex conditions, methods, expressions and classes, as well as reports long methods and long parameter lists.
  3. Coroutines: The coroutines rule set analyzes code for potential coroutines problems.
  4. Empty-Blocks: It contains rules that report empty blocks of code. Examples include empty catch blocks, empty class blocks, empty function and conditional function blocks.
  5. Exceptions: It reports issues related to how code throws and handles exceptions. For example, it has rules if you’re catching generic exceptions among other issues related to handling exceptions.
  6. Formatting: This checks if your codebase follows a specific formatting rule set. It allows checking indentation, spacing, semicolons or even import ordering, among other things.
  7. Naming: It contains rules which assert the naming of different parts of the codebase. It checks how you name your classes, packages, functions and variables. It reports the errors in case you’re not following the set conventions.
  8. Performance: It analyzes code for potential performance problems. Some of the issues it reports include the use of ArrayPrimitives or misuse of forEach loop, for instance.
  9. Potential-Bugs: The potential-bugs rule set provides rules that detect potential bugs.
  10. Style: The style rule set provides rules that assert the style of the code. This will help keep code in line with the given code style guidelines.

Each rule set contains a vast number of rules. This tutorial covers the most common rules, but don’t hesitate to check the official documentation to learn more about the rules.

Some of the rules are not active by default. You have to activate them yourself. How do you do that, you might ask? You’ll look into that in the next section.