Avoid NullPointerExceptions

This is a simple trick to avoid these nasty NullPointerExceptions:
instead of
if (myVar.equals(MY_CONSTANT))
simply write
if (MY_CONSTANT.equals(myVar))

The second form is better and more stable since it avoids NullPointerExceptions and merely will evaluate to false if myVar is null. But the first will throw a NullPointerExceptions instead. This is what I call defensive programming. Patrick at MojoKnows was a big advocate of defensive programming.

Posted by Karsten at 07.06.04 03:30 | TrackBack

Hmmm - I don't know. It seems to me that a NullPointerException usually indicates a more serious bug in the code. And your suggestion would simply mask it.

Posted by: Robb Shecter at 09.06.04 07:26

Yes, that's true. But with my suggestion you have the freedom to either deal with the bug or simply let it mask. And in some cases a null value might be a possible value. This tip helps to keep it, without running into NullPointerExceptions.

Posted by: Karsten Voges at 09.06.04 08:19

this 'trick' allows for terser code in situations where you'd not normally throw a NPE, where you could get a valid null parameter. what i mean is that if you you realize the danger of the NPE, but still want to code in the first style, you have to write something like:

if ((myVar != null) && myVar.equals(MY_CONSTANT))

whereas the second style allows a single-eval test, neater-looking code

Posted by: john at 09.06.04 17:51

This will solve the NPE within the conditional expression and just shift the NPE BUG to some other point in the code.

Posted by: Rikki at 09.06.04 18:35

This (fairly classic) trick allows for less verbose although fully understandable code, such as

public static void main (String[] args) {
String fileName="/tmp/foo";
if("-f".equals(args[0]) && args[1]!=null)

Posted by: lung at 10.06.04 15:14

People like Robb Shecter are hard-headed. Their inflexible nature generates unwanted, annoying people within a team.

Ignore Robb Shecter here.

Robb Shecter: It's a good tip by Karsten Voges AND you've to adopt and start implementing it ASAP. That's it.

Posted by: Against Robb Shecter at 14.06.04 00:43

Was browsing through blogspot when I stumbled here

Posted by: SarahSterling at 06.11.04 09:27
Post a comment

Remember personal info?