Skip to content

Commit

Permalink
Refactor MultilineLambdaItParameter rule (#4428)
Browse files Browse the repository at this point in the history
1. Simplify the check for the lambda statement size
If the lambda statement list is null, the lower than check can be eliminated.
2. Remove redundant else statement
  • Loading branch information
schalkms committed Dec 30, 2021
1 parent 779f605 commit 8d7f24e
Showing 1 changed file with 18 additions and 22 deletions.
Expand Up @@ -76,38 +76,34 @@ class MultilineLambdaItParameter(val config: Config) : Rule(config) {
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
super.visitLambdaExpression(lambdaExpression)
if (bindingContext == BindingContext.EMPTY) return
// If the lambda expression has <= 1 statements, skip check.
if (lambdaExpression.bodyExpression?.statements?.size ?: 0 <= 1) return
val size = lambdaExpression.bodyExpression?.statements?.size
if (size == null || size <= 1) return

val parameterNames = lambdaExpression.valueParameters.map { it.name }
when {
// Explicit `it`
IT_LITERAL in parameterNames ->
// Explicit `it`
if (IT_LITERAL in parameterNames) {
report(
CodeSmell(
issue,
Entity.from(lambdaExpression),
"The parameter name in a multiline lambda should not be an explicit `it`. " +
"Consider giving your parameter a readable and descriptive name."
)
)
} else if (parameterNames.isEmpty()) { // Implicit `it`
val implicitParameter = lambdaExpression.implicitParameter(bindingContext)
if (implicitParameter != null &&
lambdaExpression.hasImplicitParameterReference(implicitParameter, bindingContext)
) {
report(
CodeSmell(
issue,
Entity.from(lambdaExpression),
"The parameter name in a multiline lambda should not be an explicit `it`. " +
"The implicit `it` should not be used in a multiline lambda. " +
"Consider giving your parameter a readable and descriptive name."
)
)
// Implicit `it`
parameterNames.isEmpty() -> {
val implicitParameter = lambdaExpression.implicitParameter(bindingContext)
if (implicitParameter != null &&
lambdaExpression.hasImplicitParameterReference(implicitParameter, bindingContext)
) {
report(
CodeSmell(
issue,
Entity.from(lambdaExpression),
"The implicit `it` should not be used in a multiline lambda. " +
"Consider giving your parameter a readable and descriptive name."
)
)
}
}
else -> { }
}
}
}

0 comments on commit 8d7f24e

Please sign in to comment.