Monday, January 10, 2005

Java Tip #1 - Constant Comparison

I'm going to start writing down some of the java tidbits I've picked up over the years. I find I'm starting to forget some of them... so this serves as a permanent reminder for myself and possibly education for some. Many of these will seem trivial and I doubt any are original ideas.

When comparing a constant to a variable, always put the constant on the left side of the expression. This will prevent NullPointerExceptions and avoid extra comparisons to null.


This has the potential to generate an NPE.
public function void greeting1() {
if (test.equals("hello"))) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}

This prevents the NPE with a comparison to null.
public function void greeting2() {
if (test != null && test.equals("hello"))) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}

This is safe from an NPE & avoids the null barrier.
public function void greeting3() {
if ("hello".equals(test)) {
System.out.println("hello")
} else {
System.out.println("goodbye");
}
}

In a code review, I typically will make a developer switch to the style in greeting3 if there is a chance of an NPE. If it's already guarded by a comparison to null, I'll point it out but let the code pass review. Some people might actually prefer the explicit comparison to null for readability.







0 Comments:

Post a Comment

<< Home