The last thing you want to spend time on during a code review is a discussion on formatting. Discussing formatting is a classic example of Bikeshedding. Although formatting is essential, the rules should be set once and automated as much as possible so people donโt have to waste time discussing them. Developers should spend time on what is important, which is the functionality of the software system.
I have been using ktlint for both linting and formatting Kotlin code (๐ Difference between Linting and Formatting). While the tool is very useful, thereโs something that is bugging me: ktlint doesnโt automatically format all code that doesnโt conform to the linting rules. The easiest example is that there is a maximum line length, but running the formatter doesnโt split lines.
Having worked with ๐งน Clang Format before, which is an amazing auto formatter for C-style languages, this feels odd. It is perfectly possible to split lines according to some maximum line length, although that is not necessarily an easy problem.
Different formatters for Kotlin
Besides ktlint, there are other formatters such as ktfmt, kotlin-auto-formatter and the IntelliJ auto-formatter.
Some of the options have some downsides in my opinion:
- ktlint: as mentioned before, it doesnโt automatically wrap lines
- kotlin-auto-formatter: doesnโt seem to be well maintained (at the time of writing, the last commit was 14 months ago)
- IntelliJ auto-formatter: formatting shouldnโt depend on an IDE and should be applied through the CLI, which enables tools such as CI checks.
This leaves us with ktfmt, which according to kotlin-auto-formatter doesnโt conform to the Kotlin coding conventions. Kotlin is a very opinionated language in its conventions. It is a clear downside that ktfmt doesnโt conform and on top of that, it offers virtually 0 configuration. The reason for this is that it builds on top of google-java-format. But all in all, it does look like something worth investigating further.
In the context of this article, I did a deep dive into the documentation of google-java-format. From the documentation, I learned about ๐ The Rectangle Rule in Code Readability and wrote down a couple of learnings from code formatting that can be applied to the entire discipline of software engineering.
Conclusion
There are different formatters in the Kotlin ecosystem, each having its pros and cons. I prefer ktfmt, which is based on google-java-format. Itโs interesting to see how complex a relatively easy problem like formatting becomes once you dig deeper, but some learnings can be applied to all of Software Engineering.