Java tips: null Vs empty

To understand when to use null and when to use empty, we first need to know what are their differences. Well, null, simply means null. The object is non-existent. You will hit a nasty NPE should you try to use a null object. Typically, empty refers to data structures such as List or Collection. These data structure can contain zero or many objects. So when there’re no objects contained, the data structure is said to be empty.

The debate comes in here whereby one group of developers would argue that if the data structure does not contain any object, we could make it null, no need to instantiate an empty ArrayList or Vector. However, on careful thoughts, using null to represent empty data structures is flawed for a few good reasons.

A data structure is empty but not null. The data structure exists and hence it is capable of being used when needed. By setting it to be null, it is implying that no such data structure exists.

There’re many instances whereby you would typically iterate through a data structure to access its contents. If the data structure is set to null, you would have to do an additional null check every time you access it. This is unnecessary if you have an empty ArrayList or Vector. The for-loop would not even execute. So in realty, you have a performance gain and your code is actually more readable and compact (no need for unnecessary checks).

I would even go far enough to say that this is one of the best practices as seen in Java API. This is particularly useful when you’re providing your own API. The client code need not be defensive and could focus on accessing your returned data structure.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: