views:

231

answers:

8

I was writing some code and while unit testing I got a Null Pointer Exception...Now I'm wondering how often should we be checking that object is not null before doing get operations on it?

For example, code was:

HashMap paramMap = new HashMap();
getSqlMapClientTemplate().queryForObject("reexamination.isAuthorized", paramMap);
return ((List)paramMap.get("Return0")).get(0).toString().equalsIgnoreCase("true");

I got error on the return statement because "Return0" does not exist in the HashMap. Turns out I made a typo..it was supposed to be "Result0".

I could modify the code like this:

getSqlMapClientTemplate().queryForObject("reexamination.isAuthorized", paramMap);
String returnValue = "";
if (paramMap.get("Result0")!=null)
   returnValue = ((List)paramMap.get("Result0")).toString();
return returnValue.equalsIgnoreCase("true");

Is it a good practice to always check that the object is not null before calling any of its properties? Should we be following the A B C motto? :)

A - Always
B - Be
C - Checking

Or Is it a good practice to check when we dont know what the state of the object is (like in example above). However, if we create an object like 10 lines above and know it wont be null then we can skip the null check.

I'd love to get some links that talk about this.

+1  A: 

I typically check as late as possible, that is, as close to when its actually used as I can. I always make sure that I'm checking anything external to the application. Database connections and queries, user input, socket connections and data transmitted, file reading, etc. Anything where you're not absolutely sure it won't change.

Soviut
A: 

it's necessary to check for null each time before you intend to use it or you might get null reference exception

Omu
+14  A: 

In your case, your code had a bug because you mistyped something. You want to find bugs quickly and explicitly.

Your modified code hides the bug as a legitimate false return value - which is absolutely horrible.

Generally, it's best to organize your code in such a way that checks for null are done only where necessary (i.e. only where a value can be be null legitimately, without a bug) and only once. The first thing you can do to achieve this is to reduce the number of values that can be legitimately null through the use of null objects like empty collections.

Checking for null all over the place "just in case" is close to voodoo programming, a sign that you don't know what you're doing.

Michael Borgwardt
+1 for extraneous checking being voodoo programming
Paul McMillan
@Michael, thanks thats a good explanation of when null check should be done. but in defense of my modified code...the return type of my method is boolean so if there is an error i'd much rather have it return false (even if false is not returned because of the logic implemented) than true.
Omnipresent
It won't return anything if it throws a null pointer exception...
Platinum Azure
@platinum modified code wont throw a NPE because of the if conditon.
Omnipresent
No, you do NOT want it to return false all the time, just because you mistyped the name of the parameter. This is exactly where you want a big fat NPE.
Michael Borgwardt
A: 

Typically, you don't want to check for null very often: that is part of the benefit of having the system check for you!

A few reasons you might want to check:

  • You are validating arguments, and null is not allowed: you should check and throw a null pointer exception early, so that it doesn't trigger later when you try to use it.

  • You legitimately are using null as "option", meaning that for a given reference, you expect exactly zero or one objects to be present. (You'd use a list or other collection to represent zero or more objects. But note here that an empty list is preferable to null.)

Adam Goode
+1  A: 

You need to check ever and everywhere where null could be returned and you know about that possibility.

In your case, your code is not supposed to return at this point, so there should be no need to check for null. This is good, because it fails "early" as in your test.

BeowulfOF
A: 

In general, this is the problem that structured programming is supposed to solve. If you've defined the interfaces properly, a null value will be an invalid input at the absolute next function call.

However, the real world doesn't work like that, and the true answer will vary depending on your language of choice. Java tends to be more explicit about what is and is not a valid input, whereas python tends to trust the programmer to do the right thing, and usually has less checking.

As Michael said earlier, checking for null all over the place is terrible practice - only make checks where the value validly might be null.

Paul McMillan
A: 

Applying the Law of Demeter can help with reducing the need to check for nulls. Whenever you dig into a class you pretty much need to check for a null every time and always right before accessing the property of an object. This is the only way to guarantee the object has not disappeared and this rule changes when working with shared memory.

If you are accessing the property of a property of a property (usually because you are hacking something together) I find it handy to set up a private property within the class which access the value for you and if the object is null the property returns null in place of the expected value. These properties can then be daisy-chained in order to guarantee you never get a null reference and keeps the null checks from littering your code.

By focusing more on your own properties and not on the properties of other classes is the only way to reduce the need for null checks and this is something that is generally exemplified in good OO Design.

But for hacking, I myself have fantasied about a little syntactic sugar that could be added to the C# language where instead of:

MyObject.ItsProperty.AnotherProperty

you could say

MyObject?ItsProperty?AnotherProperty

If any of the objects are null this would simply return null rather than throw an exception. I call it the inflection operator because to read it you should put an inflection on each property making it should like a question.

Blake Taylor
A: 

To my way of thinking, there are only three cases where you should explicitly check for null in Java.

The first case is when a value may legally be null with a specific meaning. So (obviously) you need to check for null at the appropriate points so that your code does the right thing. The flip side is that it is important for APIs to clearly document the situations where a null value is a acceptable, and that an API methods should NOT return a null as a quick and dirty way of reporting an error.

The second case is the null is invalid, but you need to report the problem in some way other than an NPE. For example, the null may be a result of a missing query parameter in an HTTP request, and you ought to report it as an "400 Bad Request" rather than a "500 Internal Server Error".

The final case is where null is invalid, but it is particularly important that the null be detected early to stop the erroneous value spreading further. In this case, the problem should be reported by throwing an exception. (My preference is for a NullPointerException, but others advocate IllegalArgumentException.)

Stephen C

related questions