Detecting Kotlin Code Smells with Detekt

Hello everyone! đź‘‹ In this story I will show how to improve your Kotlin codebase with Detekt, a Kotlin Static Analysis Tool.
Detekt will analyze Kotlin code with multiple rule sets and flag the code that breaks any of its rules. Detekt improves the codebase by enforcing rule sets including complexity, naming, performance & potential-bugs among others.
When added to CI (in my case, CircleCI) it will also act as a safety net in case you try to merge code which contains Kotlin code smells.
Before starting: Make sure you have the latest Gradle (4.10.2 right now) in the gradle-wrapper.properties file.
To implement Detekt let’s start by creating a detekt.gradle
file in the root of the project.
We then add it to the top level build.gradle under the allprojects
section so it is applied to all of our modules & we also add the Detekt plugin under the plugins
section.
Next step is to create the default-detekt-config.yml
file in the root of the project, use this one. For detailed information about the config file click here.
For existing projects, ignore current issues by uncommenting the baseline line from the detekt.gradle
file and running the gradle command detektBaseline
.
That’s it! Now we can run this task from gradle:
detekt
will analyze the Kotlin code to ensure no rules are broken, it will fail otherwise. Remember to add it to your CI.
Updating Detekt
Updating Detekt means more rules & less false positives. How to do it?
- Update Detekt version from
plugins
in the top level build.gradle & sync. - Generate a new Detekt config with the gradle command
detektGenerateConfig
and compare with the existing one. - Turn the new rules on.
- Run the gradle command
detekt
to ensure your codebase is not breaking any of the new rules (if it is, rundetektBaseline
to update your ignored issues).
Check the project below 👇 if you have any doubts. Remember to add Detekt to your CI and to use the baseline feature to ignore existing issues. Detekt is highly configurable, find documentation here.