Clean compareTo methods with Google Guava « EclipseSource Blog
Basically a ComparisonChain
is just a util that provides a fluent API to write clean compareTo
methods. And, as you might agree, clean means readable and maintanable. Let’s convert the example above using Guavas ComparisonChain
.
public class Fruit implements Comparable<Fruit> { private String name; private String family; private int calories; @Override public int compareTo( Fruit otherFruit ) { return ComparisonChain.start() .compare( name, otherFruit.name ) .compare( family, otherFruit.family ) .compare( calories, otherFruit.calories ) .result(); } } |
The code that performs the checking for the result is completely gone. It’s done for us now by Guava’s implementation. In addition to the nice Interface another cool thing about ComparisionChain
’s is that they compare lazily. This means that values will only be compared if the previous comparison was zero. From my point of view the result of using this is much more readable code. As always, feel free to disagree in a comment.
Read full article from Clean compareTo methods with Google Guava « EclipseSource Blog
No comments:
Post a Comment