115 lines
2.6 KiB
Plaintext
115 lines
2.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The Kotlin `when` statement can not only be used to compare a selector against a list of values,
|
|
but also to select from a list of conditions.
|
|
|
|
This is a more readable and elegant alternative to a chain of `if` statements and should be used instead.
|
|
|
|
=== What is the potential impact?
|
|
|
|
==== Readability and Understanding
|
|
|
|
This change makes it easier to understand a function because it will reduce its complexity.
|
|
This is because a single `when` statement has less cognitive complexity than multiple `if` statements, even if it has as many cases.
|
|
|
|
== How to fix it
|
|
|
|
Refactor the chain of `if` statements into a list of conditions for a `when` statement.
|
|
Note that the order of the conditions must stay the same as in the `if` chain.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,kotlin,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
fun dispatchFunction(instance: Any) {
|
|
if (instance is Foo) {
|
|
instance.fooFunction()
|
|
} else if (instance is Bar) {
|
|
instance.barFunction()
|
|
} else if (instance is Boo) {
|
|
instance.booFunction()
|
|
} else {
|
|
throw IllegalArgumentException()
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=1,diff-type=compliant]
|
|
----
|
|
fun dispatchFunction(instance: Any) {
|
|
when (instance) {
|
|
is Foo -> instance.fooFunction()
|
|
is Bar -> instance.barFunction()
|
|
is Boo -> instance.booFunction()
|
|
else -> throw IllegalArgumentException()
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
When `threshold = 2`
|
|
|
|
[source,kotlin,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
fun compare(a: Int, b: Int): Int {
|
|
// ...
|
|
return if (a > b) { // Noncompliant
|
|
1
|
|
} else if (a < b) {
|
|
-1
|
|
} else {
|
|
0
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=2,diff-type=compliant]
|
|
----
|
|
fun compare(a: Int, b: Int): Int {
|
|
// ...
|
|
return when { // Compliant
|
|
a > b -> 1
|
|
a < b -> -1
|
|
else -> 0
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://kotlinlang.org/docs/control-flow.html#when-expression[Kotlin Docs, When expression]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://www.baeldung.com/kotlin/when[Baeldung, Guide to the “when{}” Block in Kotlin]
|
|
* https://superkotlin.com/kotlin-when-statement[Kotlin when: A switch with Superpowers]
|
|
* https://www.sonarsource.com/resources/cognitive-complexity[G. Ann Campbell, Cognitive Complexity]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Parameters
|
|
|
|
.threshold
|
|
****
|
|
|
|
----
|
|
3
|
|
----
|
|
|
|
Number of "if" after which the chain should be replaced by a "when" statement.
|
|
****
|
|
|
|
endif::env-github,rspecator-view[]
|