Showing posts with label coding practices. Show all posts
Showing posts with label coding practices. Show all posts

NullPointerException

Why write about NullPointerExceptions?

NullPointerExceptions are one of the most basic runtime errors encountered in Java programming. Learning how to fix NullPointerExceptions is a vital skill for anyone programming in Java, as any student or amateur Java programmer will encounter these errors eventually. Sadly, even some professional Java programmers are stumped by them. I hope that this article will help programmers understand what NullPointerExceptions are, why they happen, and how to fix them. And for when all else fails, I'll offer a few pointers on asking for assistance with a NullPointerException.

What is a NullPointerException?

A NullPointerException is an unchecked runtime error. As such, NullPointerExceptions do not have to be declared in a method's throws clause. Because they are not checked exceptions, it is easy to forget about them and many programmers will not make any effort to handle or avoid NullPointerExceptions until they start occurring. A NullPointerException may indicate a logical error, improper data validation, incorrect use of an API, or some other programming problem.

Why do NullPointerExceptions happen?

A NullPointerException is caused by an attempt to dereference a pointer that doesn't point to anything; the pointer is null. Here are a couple of common scenarios where NullPointerExceptions can be found:

1.    String myString = null;
2.    System.out.println(myString.length());

Here a variable, myString, is declared and initialized to null on line #1. When line #2 attempts to deference the variable myString in order to print the string's length, a NullPointerException is thrown because myString doesn't point to anything.

1.    System.out.println(aMethodThatReturnsNull().toString());

This second example is a little trickier. No variable was declared, but there is still a pointer: the return value of the method aMethodThatReturnsNull(). That fictitious (and seemingly useless) method will always return null. As we saw in the first example, attempting to dereference a null pointer and call a method on the referenced object (which is null) results in a NullPointerException.

How do you track down a NullPointerException?

To find the source of a NullPointerException, start with the stack trace. In your Java console or log file, you'll see something like this:

Exception in thread "main" java.lang.NullPointerException
	at com.foo.example.NullPointerExample.main(NullPointerExample.java:21)

The stack trace tells you what happened (NullPointerException) and where (line 21 of NullPointerExample.java). Look at that line and see if you can recognize one of the two patterns given above. Ask yourself these questions:

  1. Are you calling a method on a variable that might be null?
  2. Are you calling a method on the return value of another method, where the first method might return null?
  3. Are you absolutely sure the answer to the first two questions was "no?" NullPointerExceptions can happen for other reasons, but these two are by far the most common.

How do you ask for help with a NullPointerException?

First, put some effort into it. Although most developer communities are ready and willing to help with problems relating to the community's subject area, NullPointerExceptions are very often simple programming errors and probably off topic for anything except a Java beginners forum. So before posting and asking for help, determine if the problem is in your own code.

Once you're certain that the exception isn't arising from your code, take a look at the code that is causing the exception (see above). You might be using an API improperly. Third-party libraries may not support null parameters, for example.

If you still need help, be sure to follow these guidelines when posting on a forum or emailing colleagues directly:

  • Be polite. You're asking for other people's time, generally without paying for it.
  • Be thorough.
    • Include the stack trace from the exception.
    • Include any of your code that is relevant to the stack trace.
    • Explain what you've done to troubleshoot and detail your findings.
  • Be patient. People are busy and have their own priorities. It may take hours or days to get a reply from the community, and longer to get a free solution. If you need immediate, devoted attention, you should expect to pay for it. If you want to "bump" your message to get more attention, don't just post "bump" or "can anyone help" -- offer up some additional information to demonstrate that you're taking ownership of the problem and still working on it (nobody wants to do your job for you!). Your new findings may elicit a response. Whining about not getting a response is unlikely to help matters and can alienate the community members who could assist you.

I make this look good

There is beauty, maybe even art, in code.

A well written piece of code flows smoothly. It is thoughtfully designed, observes proper encapsulation and variable scoping, and possesses a cohesive purpose. And it is well formatted. Lines are indented in the proper places so that the eye can easily follow the path down into nested constructs -- if statements, loops, anonymous inner classes, etc. -- emerging again into the main line of processing. Not only the structure, but the meaning and intent of the code are important in its visage. Variable names are concise without being cryptic, descriptive without being verbose. Capitalization and underscores are consistently applied where (and if) appropriate. Consistency in these elements makes code easier to read, just as proper spelling and grammar make the written word more comprehensible. Being able to tell what code means and what it's supposed to do at a glance is thrilling to a coder. If something thrills you when you look at it, isn't it beautiful? Good code looks good. Sometimes the beauty comes from the simplicity of the code and other times from taking a very complex algorithm and rendering it in a longer and more eloquent fashion which makes the complexity melt away as each line leads you by the hand through the intricate process.

The appearance of code is something that's been on my mind recently. In a discussion today on the GWT Contributor forum, I argued that certain proposed coding style guidelines disturbed the Feng Shui of code without adding value. It may not have been my most substantive argument of all time, but I think there's something of importance in that pithy reference to what many in the western world may think of as nothing more than an interior decorating fad. Each character in each line of code should blend harmoniously and purposefully with its surroundings. Even an extra space, or lack of one, could alter the careful balance of code without necessarily impacting its function. But that loss of balance harms the readability of code. Code that is less readable is less beautiful.

I always try to write my code in a way that appears neat and tidy. I've looked back on code I wrote years ago and thought to myself "damn, that's sexy." Sometimes (maybe more often, depending on how far back I wrote the code in question) instead I wonder what the Hell I was thinking when I wrote it. But most of those head-scratchers can be polished into more appealing code. It could simply be that my personal preference in matters of style and convention have changed, and applying those new preferences is all it takes.

Like fine art, music, and other things in which beauty can be found, beautiful code is often a matter of taste. But whether you prefer C++, Java, Lisp, .NET, Ruby, PHP, ColdFusion, Lua, or any of the myriad other varieties, take a moment sometime to appreciate the code. And please, for the sake of the code-lover who comes after you, strive to make beauty in your work -- appearances count.