Return empty objects, not nulls

By , last updated April 6, 2018

We continue to cover small programming basics topic and in this article we will talk about returning values from methods.

It’s uncommon to see methods that return null if none of the if statements are true. Here is an example of a method in Java programming language that return null if no person was found in the database:

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

There is no reason to make a Person object where there is nothing 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>

*