Skip to main content

How empty can you be?

·2 mins

Working with collections is pretty standard and straightforward work for any developer, but there seems to be a bit of confusion regarding the isEmpty() method. In this post, I will try to explain why there is an isEmpty() method, why the implementors chose to write a method to check for empty and not a method to check for not empty.

Why empty is important #

I will skip the discussion about returning null, I might do a post about that later, but personally I don’t like to return null. If a method should return a collection, I will return an empty collection, which is the proper way to code, which I will explain below.

The importance of empty is that it represent an abnormal case. Normally you would expect a method returning a collection of data, getting an empty collection back, represents a branch in your code, something that needs attention and be dealt with.

Dealing with collections with data #

This is how you normally deal with collections

for (String s : myCollection) {
	doSomethingWithS(s);
}

If the collection is empty, the loop will just be skipped and it will continue execution below it. If you don’t need a special flow to handle empty collections, this is the way to do it, but what if you need to supply default data if the collection is empty?

if (myCollection.isEmpty()) {
	myCollection = populateCollectionWithDefaultData(myCollection);
}

for (String s : myCollection) {
	doSomethingWithS(s);
}

Why isn’t there a isNotEmpty() method? #

The answer is simple, there’s no need for it. You would expect data in your collection, that’s the normal case.

Conclusion #

The isEmpty() method is only important if you need to treat an empty collection differently from your normal flow. Java is perfectly fine with iterating over empty collections, it simply skips them. But if the code following the iteration somehow depends on there being data in that collection, use isEmpty() to handle that case.