Categories
java ruby

if they’re the same thing do nothing, if they’re different things do something

So I’m inspired by this post at the Daily WTF. The problem happens quite a lot in Java and I’m sure I’ve come across it myself at least once.

The central issue is, how do you safely (i.e. no NPE!) and cleanly compare two values where both could be null?

It’s only a small challenge, I grant you, but the code sample they have at WTF will return false if two Boolean’s have the same value, including nulls.

Indeed there’s a million ways to do this, but concisely and expressively is what we’re after. I’ve got two:

  1. if (value1 == value2) will work if all the Boolean’s in the system were created with the Boolean.valueOf() function. In which case there won’t be zillions of tiny Boolean objects floating around, just two, and hence instance comparisons via == on the values are ok. However, would you trust all your colleagues not to somehow contravene this and slip in a new instance somewhere that totalled your code? I know I wouldn’t.
  2. (value1 == null ? value2 != null : value1.equals(value2)) is the safest and I think cleanest approach.

It goes to show that the ‘null’ object in Java is not fully formed. In languages like Ruby ‘nil’ is a first-class object with its own methods. Hence in Ruby we could have just written: value1==value2. We wouldn’t have to care about NPE’s because there’s no such thing but also because:

irb(main):037:0> nil.==(false)
=> false