
In addition, it's just annoying that these checks get in the way of the business logic. Unfortunately, we need a lot of boilerplate code to make sure we don't get a NullPointerException. However, you can see that the code in Listing 1 quickly becomes very ugly due to the nested checks. Soundcard soundcard = computer.getSoundcard() What can you do to prevent unintended null pointer exceptions? You can be defensive and add checks to prevent null dereferences, as shown in Listing 1: I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement." It was the invention of the null reference in 1965. To give some historical context, Tony Hoare-one of the giants of computer science-wrote, "I call it my billion-dollar mistake. Imagine if your program was running on a customer's machine what would your customer say if the program suddenly failed? Unfortunately, this means the call to getUSB() will try to return the USB port of a null reference, which will result in a NullPointerException at runtime and stop your program from running further. So what is the result of getSoundcard()?Ī common (bad) practice is to return the null reference to indicate the absence of a sound card. However, many computers (for example, the Raspberry Pi) don't actually ship with a sound card. String version = computer.getSoundcard().getUSB().getVersion() What's possibly problematic with the following code? Let's consider a nested object structure for a Computer, as illustrated in Figure 1.įigure 1: A nested structure for representing a Computer Let's start with an example to see the dangers of null. Java SE 8 introduces a new class called that can alleviate some of these problems.

Joking aside, the null reference is the source of many problems because it is often used to denote the absence of a value. Make your code more readable and protect it against null pointer exceptions.Ī wise man once said you are not a real Java programmer until you've dealt with a null pointer exception.
