Code Clean UP Tips: Coding Standard Formatting: Exception Handling: Don't Return Null and Don’t Pass Null

5 views
Skip to first unread message

Arjun Sridhar UR

unread,
Mar 2, 2015, 2:42:43 AM3/2/15
to IN CMPS Saheer, IN CMPS Saheer, IN CMPS Ebinezer, IN CMPS Ebinezer, IN IT CMPS Mano Chitra, satya rajasheharan, IN CMPS Karthik Dhanaraj, arjunsr...@googlegroups.com
Code Clean UP Tips:: Coding Standard Formatting:- Exception Handling: Don't Return Null and Don’t Pass Null

Don’t Return Null
===============
I  think that any discussion about error handling should include mention of the things we
do that invite errors. The first on the list is returning null. I can’t begin to count the number
of applications I’ve seen in which nearly every other line was a check for null. Here is
some example code:

public void registerItem(Item item) {
  if (item != null) {
    ItemRegistry registry = peristentStore.getItemRegistry();
      if (registry != null) {
      Item existing = registry.getItem(item.getID());
      if (existing.getBillingPeriod().hasRetailOwner()) {
       existing.register(item);
       }
    }
  }
}
If you work in a code base with code like this, it might not look all that bad to you, but it is
bad! When we return null, we are essentially creating work for ourselves and foisting
problems upon our callers. All it takes is one missing null check to send an application
spinning out of control.
Did you notice the fact that there wasn’t a null check in the second line of that nested
if statement? What would have happened at runtime if persistentStore were null? We
would have had a NullPointerException at runtime, and either someone is catching
NullPointerException at the top level or they are not. Either way it’s bad. What exactly
should you do in response to a NullPointerException thrown from the depths of your application?
It’s easy to say that the problem with the code above is that it is missing a null check,
but in actuality, the problem is that it has too many. If you are tempted to return null from
a method, consider throwing an exception or returning a SPECIAL CASE object instead. If
you are calling a null-returning method from a third-party API, consider wrapping that
method with a method that either throws an exception or returns a special case object.

In many cases, special case objects are an easy remedy. Imagine that you have code
like this:
List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
Right now, getEmployees can return null, but does it have to? If we change getEmployee so
that it returns an empty list, we can clean up the code:
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
Fortunately, Java has Collections.emptyList(), and it returns a predefined immutable list
that we can use for this purpose:
public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}
If you code this way, you will minimize the chance of NullPointerExceptions and your
code will be cleaner.

Don’t Pass Null
==============
Returning null from methods is bad, but passing null into methods is worse. Unless you
are working with an API which expects you to pass null, you should avoid passing null in
your code whenever possible.
Let’s look at an example to see why. Here is a simple method which calculates a metric
for two points:
public class MetricsCalculator
{
public double xProjection(Point p1, Point p2) {
return (p2.x – p1.x) * 1.5;
}
}
What happens when someone passes null as an argument?
calculator.xProjection(null, new Point(12, 13));
We’ll get a NullPointerException, of course.
How can we fix it? We could create a new exception type and throw it:
public class MetricsCalculator
{
112 Chapter 7: Error Handling
public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw InvalidArgumentException(
"Invalid argument for MetricsCalculator.xProjection");
}
return (p2.x – p1.x) * 1.5;
}
}
Is this better? It might be a little better than a null pointer exception, but remember, we
have to define a handler for InvalidArgumentException. What should the handler do? Is
there any good course of action?
There is another alternative. We could use a set of assertions:
public class MetricsCalculator
{
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x – p1.x) * 1.5;
}
}
It’s good documentation, but it doesn’t solve the problem. If someone passes null, we’ll still have a runtime error.
In most programming languages there is no good way to deal with a null that is
passed by a caller accidentally. Because this is the case, the rational approach is to forbid
passing null by default. When you do, you can code with the knowledge that a null in an
argument list is an indication of a problem, and end up with far fewer careless mistakes.
Conclusion
Clean code is readable, but it must also be robust. These are not conflicting goals. We can
write robust clean code if we see error handling as a separate concern, something that is
viewable independently of our main logic. To the degree that we are able to do that, we can
reason about it independently, and we can make great strides in the maintainability of our
code.


Reply all
Reply to author
Forward
0 new messages