Return empty objects, not nulls

By , last updated October 17, 2010

It’s uncommon to see methods like this>

public Person findPerson() {
   if(someService) [
     return someService.getPerson();
   } 
   return null;
}

There is no reason to make a Person object where there are no persons found. But doing so requires extra code in the client to handle the null value. This becomes a problem if a client is, for example, a GUI:

somePage.jsp
<%
  ...
  Person person = myService.findPerson();
%>
<table>
   <tr>
      <td>${person.name}</td>
      <td>${person.address}</td>
      <td>${person.numberOfPurchases}</td>
   </tr>
</table>

The result of such code in cases where the person cannot be found is Server error. So, there is no reason ever to return null from an object-valued method instead of returning an empty object. Especially if you deal with arrays and collections.

Senior Software Engineer developing all kinds of stuff.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*