Guava: how smart is ComparisonChain ?

760 views
Skip to first unread message

fishtoprecords

unread,
Jul 22, 2010, 4:31:12 PM7/22/10
to guava-discuss
I looked at the source code, and its so concisce that its hard to
follow, r answer this fundamental question.
How smart is it?
Do I still need to start off with these two lines?

public int compareTo(Foo foo) {
if (oA == null) return 1;
if (oA == this) return 0;
return ComparisonChain.start()
....

or is the null and identity check built it?

Colin Decker

unread,
Jul 22, 2010, 4:46:13 PM7/22/10
to guava-...@googlegroups.com
ComparisonChain just simplifies comparing multiple properties of two non-null objects in order. Since typically you call it something like:

return ComparisonChain.start()
   .compare(getFoo(), other.getFoo())
   .compare(getBar(), other.getBar())
   .result();

you're obviously going to get a NPE if other is null.

It doesn't do any null or identity check. That's up to you if you feel the need to do them. If you avoid having null references in your collections or are using the chain with an Ordering with nullsFirst() or nullsLast() you don't need to worry about null. Identity doesn't seem like something you should really have to worry about much at all.

Colin


--
guava-...@googlegroups.com.
http://groups.google.com/group/guava-discuss?hl=en
unsubscribe: guava-discus...@googlegroups.com

This list is for discussion; for help, post to Stack Overflow instead:
http://stackoverflow.com/questions/ask
Use the tag "guava".

Chris Povirk

unread,
Jul 22, 2010, 5:40:57 PM7/22/10
to guava-...@googlegroups.com
As Colin said, there's no null or identity check. Just a note,
though: I'd discourage including a null check at all, as it's
surprising for a.compareTo(b) to succeed but for b.compareTo(a) to
fail. In fact, it's disallowed: "Note that null is not an instance of
any class, and e.compareTo(null) should throw a NullPointerException
even though e.equals(null) returns false." A compareTo() method that
accepts null may work in some cases, but it's a problem waiting to
happen. For example, treeSet.contains(null) isn't obligated to call
existingNonNullEntry.compareTo(null) instead of
null.compareTo(existingNonNullEntry), so code that works today may
fail in the next version. Colin's approach of using a Comparator --
Ordering.natural().nullsFirst() or similar -- is the safe way to
permit nulls.
Reply all
Reply to author
Forward
0 new messages