Rules / Style / prefer-is-empty
prefer-is-empty
Flags .length comparisons equivalent to a .isEmpty check.
Collections and strings expose an isEmpty getter that states intent
directly and, for lazy iterables, can be cheaper than computing the full
length. Comparing length against a constant forces the reader to decode
the boundary, so list.isEmpty should replace forms such as length == 0,
length < 1, and length <= 0, together with their operand-swapped mirrors
(0 == length, 1 > length, 0 >= length). The rule matches any .length
property access against the relevant integer literal; it does not attempt to
confirm the receiver actually offers isEmpty.
Invalid
example.dartdart
void bad() {
if (list.length == 0) return;
if (0 == items.length) return;
if (str.length < 1) return;
if (map.length <= 0) return;
if (1 > set.length) return;
if (0 >= names.length) return;
}
Use 'isEmpty' instead of comparing 'length' to 0.
1void bad() {
2 if (list.length == 0) return;
∙
Use 'isEmpty' instead of comparing 'length' to 0.
2 if (list.length == 0) return;
3 if (0 == items.length) return;
∙
Use 'isEmpty' instead of comparing 'length' to 0.
3 if (0 == items.length) return;
4 if (str.length < 1) return;
∙
Use 'isEmpty' instead of comparing 'length' to 0.
4 if (str.length < 1) return;
5 if (map.length <= 0) return;
∙
Use 'isEmpty' instead of comparing 'length' to 0.
5 if (map.length <= 0) return;
6 if (1 > set.length) return;
∙
Use 'isEmpty' instead of comparing 'length' to 0.
6 if (1 > set.length) return;
7 if (0 >= names.length) return;
∙
Valid
example.dartdart
void good() {
if (list.isEmpty) return;
if (items.length == 2) return;
if (str.length > 0) return;
if (map.length != 0) return;
if (set.length >= 1) return;
if (count == 0) return;
}
How to configure
Set the severity of prefer-is-empty in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"style": {
"prefer-is-empty": "error"
}
}
}
}