
Co-authored-by: nicolas-gauthier-sonarsource <121794895+nicolas-gauthier-sonarsource@users.noreply.github.com> Co-authored-by: Fred Tingaud <95592999+frederic-tingaud-sonarsource@users.noreply.github.com>
46 lines
1.3 KiB
Plaintext
46 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When you call `isEmpty()`, it clearly communicates the code's intention, which is to check if the collection is empty. Using `size() == 0` for this purpose is less direct and makes the code slightly more complex.
|
|
|
|
Moreover, depending on the implementation, the `size()` method can have a time complexity of `O(n)` where `n` is the number of elements in the collection. On the other hand, `isEmpty()` simply checks if there is at least one element in the collection, which is a constant time operation, `O(1)`.
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class MyClass {
|
|
public void doSomething(Collection<String> myCollection) {
|
|
if (myCollection.size() == 0) { // Noncompliant
|
|
doSomethingElse();
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
Prefer using `isEmpty()` to test for emptiness over `size()`.
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public class MyClass {
|
|
public void doSomething(Collection<String> myCollection) {
|
|
if (myCollection.isEmpty()) {
|
|
doSomethingElse();
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|