Refactor + rename util function inside MandatoryBracesIfStatement rule#3908
Conversation
| this.`else` !is KtIfExpression && | ||
| this.`else` !is KtBlockExpression && | ||
| this.`else` !is KtWhenExpression | ||
| private fun hasCorrectElseType(expression: KtExpression): Boolean = |
There was a problem hiding this comment.
Maybe you have better ideas for the function name.
There was a problem hiding this comment.
hasCorrectElseType is really wrong. It should be hasIncorrectElseType.
I played around with it a little bit and realized that we do allow a when expression within the else branch but not in the then branch. It may not be something that is used often, but I don't see a reason why this is compliant
fun f(i: Int) {
if (true) {
println()
} else when(i) {
1 -> println(1)
else -> println()
}
}while this is not
fun f(i: Int) {
if (true) when(i) {
1 -> println(1)
else -> println()
} else when(i) {
println()
}
}I ended up with
val thenExpression = expression.then
if (mustBeOnSameLine(thenExpression) && hasNewLineAfter(expression.rightParenthesis)) {
report(CodeSmell(issue, Entity.from(thenExpression ?: expression), DESCRIPTION))
}
val elseExpression = expression.`else`
if (mustBeOnSameLine(elseExpression) && hasNewLineAfter(expression.elseKeyword)) {
report(CodeSmell(issue, Entity.from(elseExpression ?: expression), DESCRIPTION))
}
private fun mustBeOnSameLine(expression: KtExpression?): Boolean {
return expression != null &&
expression !is KtIfExpression &&
expression !is KtBlockExpression &&
expression !is KtWhenExpression
}There was a problem hiding this comment.
Thanks for the suggestion. I have the feeling that experimental contracts are a bit overkill in this case. I'm also not sure whether we want experimental features being used in detekt's code base.
There was a problem hiding this comment.
I totally agree. I updated the comment above removing the contract.
Codecov Report
@@ Coverage Diff @@
## main #3908 +/- ##
============================================
+ Coverage 83.53% 83.56% +0.03%
+ Complexity 3120 3118 -2
============================================
Files 456 456
Lines 8996 8995 -1
Branches 1753 1750 -3
============================================
+ Hits 7515 7517 +2
Misses 565 565
+ Partials 916 913 -3
Continue to review full report at Codecov.
|
| report(CodeSmell(issue, Entity.from(expression.`else` ?: expression), DESCRIPTION)) | ||
| val elseExpression = expression.`else` | ||
| if (elseExpression != null && hasCorrectElseType(elseExpression) && hasNewLine(expression.elseKeyword)) { | ||
| report(CodeSmell(issue, Entity.from(elseExpression), DESCRIPTION)) |
There was a problem hiding this comment.
By doing the null check before, we can safely pass the else variable here.
No description provided.