Go to >> Java Tutorials
Target audience: Beginners
Every day we come across at least a method that would return a list of objects or null.For example see the following code block.
Employee employee = ....
List children = employee.getChildren();
if (children != null) {
for (Child child : children) {
// do something....
}
}
Here, the getChildren() of Employee is prone to error because it would return null object. The caller always need to check null before proceeding the returned list. We can try to reduce these situation by returning an empty list if there are nothing to return when a list is expected to be returned. Suppose if the getChildren() return empty list if there is nothing to return, then the caller’s code will be as bellow
Employee employee = ....
List children = employee.getChildren();
for (Child child : children) {
// do something....
}
This looks neat and reduces the possibilities to make errors.
Some people might say that creating an Empty list and returning every time if there is nothing to return, will be costly and unnecessarily creating objects. True, and we are not going to create empty object every time. Collections API has static final empty list which can be used to return instead. Look at code shown bellow to know how it can be done
This style can be used for any other collections and of course arrays too. It's not restricted only to List
class Employee {
public List getChildren() {
...
if(children == null){
return Collections.EMPTY_LIST;
}
....
}
...
}
Did not know that Kannan, thanx
ReplyDelete