java – What is the best way to check for a non-empty collection?

Question:

I wonder how it is more competent to write a check that the collection is not empty, following the principle of clean code?

if(!col.isEmpty())

Or

if(col.size() > 0)

Or

if(col.get(0) != null)

You may not notice the insidious exclamation mark, but I read somewhere on enSO that it reads better this way, but it seems to me that the second option is the most readable.

So, how is it better?

Answer:

if(col.size() > 0)
and
if(col.get(0) != null)

not an option at all.

if(!col.isEmpty()) is more appropriate, but as you correctly noted, the "!" often you can not notice, because our brain does not work well with denial. Because of this, sometimes it will be difficult to find an error in the code.

You are talking about clean code. In such situations, I often, even almost always, use refactoring, or rather, I extract this condition into a method (Extract method) and call the method depending on which collection I use:

For instance,

if(!children.isEmpty()) {
    // do something
}

!children.isEmpty() and I'm pulling it into the hasChildren() method.

if (hasChildren()) {
    // do something
}

private boolean hasChildren() {
    return !children.isEmpty();
}

Such code is better readable and does not confuse another programmer who will work with your codes.

Here are more options:
!orders.isEmpty() -> hasOrders() . If the orders are empty, then nothing has been ordered.
!playlist.isEmpty() -> hasPlaylist() . If the user did not add anything to the playlist at all, then he (she) does not have a playlist.
etc.

Scroll to Top