Skip to main content

Best practice : null vs empty Collection ?

No replies
rohit.sharma
Offline
Joined: 2012-09-29
Points: 0

I had a discussion over a review comment with my reviewer regarding checking for null value v/s sending empty collection,
but we didn't come to conclusion.

Below is an abstract of the piece of code under discussion:

First piece of code is what my reviewer suggested and second is the one which I think how it should be:

CODE 1:::
public class SomeClass {
private Set users;

public Set getUsers() {
return users;
}

public String computeUsersData() {
Set users = getUsers();
if (CustomUtils.isNotNullorEmpty(users)) {
for (String user: users) {
// Some business logic here
}
}
return outputData;
}
}

CODE 2:::
public class SomeClass {
private Set users;

public Set getUsers() {
if (users == null)
return newHashSet();
else
return users;
}

public String computeUsersData() {
Set users = getUsers();
for (String user: users) {
// Some business logic here
}
return outputData;
}
}

As per my reviewer:
1. The second code will generate extra objects (i.e. empty set) in the system/memory.

As per me :
1. The new empty set will be a strong contender for Garbage collection after computeUsersData finishes.
2. The second piece of code is better to scheme/read.
3. "Premature optimisation is the root of all evil"

Please provide your thoughts.