Description
The len_without_is_empty
lint fires on private types, but adding an is_empty
method as suggested can lead to the is_empty
method raising the dead_code
lint.
For example, this code gives a len_without_is_empty
warning on Foo.len()
:
struct Foo;
impl Foo {
fn len(&self) -> usize { // warning: item `Foo` has a `.len(_: &Self)` method, but no `.is_empty(_: &Self)` method. Consider adding one, #[warn(len_without_is_empty)] on by default
unimplemented!()
}
}
fn main() {
println!("{}", Foo.len());
}
If the code is modified to add an is_empty
method, then Foo.is_empty
raises a dead_code
warning.
struct Foo;
impl Foo {
fn is_empty(&self) -> bool { // warning: method is never used: `is_empty`, #[warn(dead_code)] on by default
unimplemented!()
}
fn len(&self) -> usize {
unimplemented!()
}
}
fn main() {
println!("{}", Foo.len());
}
Therefore, if the programmer doesn't need an is_empty
method, he or she is faced with a dilemma: either silence the len_without_is_empty
lint, or add the is_empty
method and silence the dead_code
lint. We could avoid this dilemma by not raising the len_without_is_empty
lint in the first place if the is_empty
would raise a dead_code
warning; instinctively, I would check if the type is private (i.e. not exported from the crate), but I don't know if that's enough.
Also, I noticed that the len_zero
lint doesn't fire if there's no is_empty
method on the type. By applying the suggestion above, the len_without_is_empty
would not fire and the len() == 0
would not raise any warnings. Perhaps the len_zero
lint could be adjusted to also fire when the len_without_is_empty
lint was silenced, or the len_without_is_empty
lint should fire only if one of the patterns len_zero
looks for is found and the type doesn't have an is_empty
method yet. The idea is to suggest adding the is_empty
method only when it's needed. :)