77 lines
1.6 KiB
Plaintext
77 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When you call `isEmpty` or `isNotEmpty`, it clearly communicates the code's intention, which is to check if the collection is empty. Using `.length == 0` for this purpose is less direct and makes the code slightly more complex.
|
|
|
|
The rule also raises issues if the comparisons don't make sense. For example, `length` is always 0 or higher, so you don't need to write the following conditions:
|
|
|
|
[source,dart]
|
|
----
|
|
void fun(List<int> myList) {
|
|
if (myList.length >= 0) { // Noncompliant, the condition is always true
|
|
// do something
|
|
}
|
|
|
|
if (myList.length < 0) { // Noncompliant, the condition is always false
|
|
// do something
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,dart,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void fun(List<int> myList) {
|
|
if (myList.length == 0) { // Noncompliant
|
|
// do something
|
|
}
|
|
|
|
if (myList.length != 0) { // Noncompliant
|
|
// do something
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,dart,diff-id=1,diff-type=compliant]
|
|
----
|
|
void fun(List<int> myList) {
|
|
if (myList.isEmpty) {
|
|
// do something
|
|
}
|
|
|
|
if (myList.isNotEmpty) {
|
|
// do something
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* Dart Docs - https://dart.dev/tools/linter-rules/prefer_is_empty[Dart Linter rule]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Use 'isEmpty'/'isNotEmpty' instead of 'length' to test whether the collection is 'empty'/'not empty'.
|
|
* The comparison is always 'true'/'false' because the length is always greater than or equal to 0.
|
|
|
|
=== Highlighting
|
|
|
|
The condition of the `if` statement.
|
|
|
|
'''
|
|
|
|
endif::env-github,rspecator-view[]
|