Kotlin and static code analysis using detekt

2 minute read

What is Static Code Analysis?

Static code analysis is a method of debugging by examining source code before a program is run. It’s done by analyzing a set of code against a set (or multiple sets) of coding rules.

In this article, we will explore detekt. Android has a lot of static code analysis tools. Detekt can improve the codebase by enforcing a set of rules like complexity, naming, etc. Then we can apply Git-hook to do checking before Git push. Also can integrate into the CI, like checking when someone created PR.

Feature

  • Code smell analysis for your Kotlin projects
  • Complexity report based on logical lines of code, McCabe complexity, and amount of code smells
  • Highly configurable (rule set or rule level)
  • Suppress findings with Kotlin’s @Suppress and Java’s @SuppressWarnings annotations
  • Specify code smell thresholds to break your build or print a warning
  • Code Smell baseline and ignore lists for legacy projects
  • Gradle plugin for code analysis via Gradle builds
  • SonarQube integration
  • Extensible by own rule sets and FileProcessListener’s
  • IntelliJ integration

Let’s setup it

First of all, add the following dependency to your project-level build.gradle:

1classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.19.0"

Second, create a file detekt.gradle at root project, make sure the latest version of Detekt

1apply plugin: "io.gitlab.arturbosch.detekt"
2
3detekt {
4    config = files("${project.rootDir}/detekt.yml")
5    parallel = true
6}

Then, create detekt.yml at root project. You can copy from default-detekt-config.yml

Finally, the config above can apply to all project modules. Copy code below to your project-level build.gradle

1subprojects {
2    afterEvaluate { project ->
3        project.apply from: '../detekt.gradle'
4    }
5}

Using Detekt

Now the interesting part is to run the detekt command to check the health of our codebase.

1./gradlew detekt

Better integrating detekt when setup project

Yes, detekt better when we start a new project, that can be easier to create the rules. The developers can follow the rules when developing. Different when we apply on Ongoing project. We will get many errors because many rules are not implemented. However, we can decide on which rule sets we need and enable only those at the beginning, and the rest can be included as we progress.