ComparisonChain with nullsFirst() and nullsLast() methods.

1,526 views
Skip to first unread message

Roman Ženka

unread,
Dec 13, 2010, 9:37:16 AM12/13/10
to guava-discuss
Hello,

I would like to use ComparisonChain to implement compareTo methods on
my objects.

However, ComparisonChain requires all values to be non null, otherwise
it throws an NPE. Not all fields of my objects are non-null (I think
that is valid) and I still need to compare them (I think that is a
valid use, too).

I modified the ComparisonChain class, adding nullsFirst() and
nullsLast() methods that simply return a slightly different instance
of the ComparisonChain guaranteed not to throw an NPE. I find this
very convenient.

Is there something profoundly wrong with this idea? Would you consider
adding these methods if I send a patch?

Kevin Bourrillion

unread,
Dec 13, 2010, 10:35:05 AM12/13/10
to Roman Ženka, guava-discuss
You can handle nulls using

  .compare(left.nullableValue, right.nullableValue, Ordering.natural().nullsFirst())

We prefer users do this over having to add two more methods dedicated to the null case.



--
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".



--
Kevin Bourrillion @ Google
http://guava-libraries.googlecode.com

Reply all
Reply to author
Forward
0 new messages