Java : "xx".equals(variable) better than variable.equals("xx") , TRUE?

Xerg picture Xerg · Jul 13, 2010 · Viewed 8.3k times · Source

I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.

Recomendation:

String variable;

"xx".equals(variable) // OK

variable.equals("xx") //Not recomended

Because prevents appearance of NullPointerException that are not controlled

Is this true?

Answer

Mark Byers picture Mark Byers · Jul 13, 2010

This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.

  • I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
  • It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).

But:

  • It makes your code harder to read: "If blue is the sky..."
  • If you have just checked that your argument is not null on the previous line then it is unnecessary.
  • If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.

Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.