rspec/rules/S1155/java/rule.adoc
Yassin Kammoun 1007cc1b15
Modify S1155: Migrate to LaYC
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>
2023-10-19 13:33:00 +00:00

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[]