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:
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
void fun(List<int> myList) {
if (myList.length == 0) { // Noncompliant
// do something
}
if (myList.length != 0) { // Noncompliant
// do something
}
}
Compliant solution
void fun(List<int> myList) {
if (myList.isEmpty) {
// do something
}
if (myList.isNotEmpty) {
// do something
}
}