rspec/rules/S6529/kotlin/rule.adoc

55 lines
1.7 KiB
Plaintext

== Why is this an issue?
The expression can be simplified using one of the functions `isEmpty`, `isNotEmpty` or `isNullOrEmpty`.
=== What is the potential impact?
==== Readability and Understanding
This change makes the code more concise and easier to understand.
The additional comparison operator would increase the complexity of the expression
while not offering any benefit.
The function names `isEmpty`, `isNotEmpty` and `isNullOrEmpty` are descriptive on the other hand,
so it is evident to readers what the purpose of the expression is.
== How to fix it
Replace
* `collection.size == 0`, `collection.count() == 0` or `!collection.isNotEmpty()` with `collection.isEmpty()`
* `collection.size != 0`, `collection.count() != 0` or `!collection.isEmpty()` with `collection.isNotEmpty()`
* `collection == null || collection.size == 0` or `collection == null || collection.count() == 0` with `collection.isNullOrEmpty()`
=== Code examples
==== Noncompliant code example
[source,kotlin]
----
val list = listOf(5,2,9,6,8,2,5,7,3)
----
[source,kotlin,diff-id=1,diff-type=noncompliant]
----
val hasElemenents = !list.isEmpty() // Noncompliant, use isNotEmpty()
val hasNoElemenents = list.count() == 0 // Noncomplient, use isEmpty()
fun isNullOrEmpty(list: List<Int>?): Boolean = list == null || list.size == 0 // Noncompliant, use isNullOrEmpty
----
==== Compliant solution
[source,kotlin,diff-id=1,diff-type=compliant]
----
val hasElemenents = list.isNotEmpty() // Compliant
val hasNoElemenents = list.isEmpty() // Compliant
fun isNullOrEmpty(list: List<Int>?): Boolean = list.isNullOrEmpty() // Compliant
----
== Resources
=== Documentation
* https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/[Kotlin API Docs, Package kotlin.collections]