Given:
- I started working in a new team on a greenfield project which has 100% Kotlin code base
- Team members mostly have Java experience
- By single-line
if
-statement I mean the following:
if (list.isEmpty) throw IllegalArgumentExpression()
The problem:
I am arguing with my team mate if the above one-liner should be considered as a style violation in our Kotlin code or not. He insists that any if-block requires curly braces, while I do not think so.
For me, having recent Ruby experience, where I’ve seen a lot of:
raise 'Invalid input' if list.empty?
the above Kotlin one-liner looks so natural, that I was very surprised it can be considered as a style violation.
I decided to check what are the Java rules for most widely known Checkstyle configurations (Google and Oracle Java code styles). I was surprised, that both Checkstlyle Java configs have a NeedBraces
rule enabled for if-statements.
But while this is true for old Java code styles, I still do not think we should bring it to Kotlin. In Kotlin world there are ktlint and detekt tools for checking formatting and none of them with default config gets triggered on a single-line if
-statement. By default, detekt only complains on multi-line if-statements without curly braces:
if (list.isEmpty)
throw IllegalArgumentExpression()
and I agree with it. This is a very old rule for most of the languages and the motivation for it is well-known. Adding the 2nd statement with the same level of indentation as the 1st one won’t work as you might expect.
So, in my opinion one-line if-statement without curly-braces is fine, while multi-line if-statement without braces is error-prone and should be avoided.
There is another argument my team mate uses to convince me that single-line if
-statement without braces is bad. When I type the following code:
fun someFunction(input: List<String>) {
if (input.isEmpty) throw IllegalArgumentException("Input can't be empty")
if (someFlagWithQuiteLongName) {
return delegate.computeResultWithTheFunctionHavingVeryLongNameWhichWillExceed120CharsWhenUsedOnOneLineWithIfStatement(input)
}
}
he says that I am inconsistent with myself, because for 1st condition I do not use curly braces, and right after that I do. The only reason for the 2nd multi-line if-statement above is obvious: it does not fit the default 120 chars line length, so I split my if-statement to multiple lines, where I do use curly braces for the reasons already described above.
If the goal is to write the modern Kotlin code (let’s forget about past Java experience) following the official Kotlin code style (or if it does not answer the question, using the most widely adopted style), should we enforce curly braces for single-line if-statements (like old Java code styles do) or allow single-line if
-statements without {}
?