Android code style checks

Kalaiselvan
2 min readApr 17, 2020

--

Code style checks are necessary in order to maintain the code clean and formatted. Especially it would become cumbersome when code style checks has to be carried out in a project where team size is large. In order to resolve this problem we can configure git pre-commit hooks and spotless plugin in our apps.

Let’s start with git hooks first:

Once you hit git commit command and also if you have configured any git hooks(like pre-commit) then pre-commit script executes first followed by commit. By this way you are adding a check before committing the code to the repository. In the pre-commit hooks we can specify checks for branch name conventions, empty lines between the code, unused imports etc., To configure git hooks in the project, add pre-commit file in the project root folder.

This pre-commit script checks for the proper branch name as specified in the regex and runs spotless.

In order to get pre-commit properly executed we have to add few lines of code in top-level build gradle as well.

Now we have to set up spotless plugin and add some rules:

In top level build gradle and the classpath as given below

“com.diffplug.spotless:spotless-plugin-gradle:3.28.1”

Then add the spotless gradle file in the project folder

Finally invoke this plugin in the app level build gradle file

apply from: "$rootDir/spotless.gradle"

Now you are good to go. Whenever you commit the code, pre-commit script runs first and check for the errors in the branch naming convention and spotless is executed to check for any issues in the code style and formatting.

To auto fix the formatting issues found by spotless, you can run

./gradlew spotlessApply

Cheers….

--

--

Kalaiselvan

Mobile application engineer| Android tutor| Aviation Enthusiasts