Search code examples
javacomparablevalue-objects

Java Value Object Definition


I am investigating Java Value Objects for educational purposes.

What I don't understand is why no one mentions (in same breath) having Java Value Objects implement Comparable?

If Java Value Objects have to have "correct" HashCode & Equals for equality reasons why don't they also have to have Comparable CompareTo method?

Here's my thought process. Instances of Value Objects will be tested for being equal therefore they require correct equals/hashcode. Value Objects could be stored in "hash" collections, again Hashcode method need. So why not add in Comparable so they can be keys in Ordered collections?


Solution

  • I think the main reason is that for any value object you specify, there really is one and only one definition of equality, whereas there could be multiple ways to order instances of it. The unique definition of equality necessitates overriding equals() (if the default does not suffice.) Once you do that, you need to provide the matching hashCode() implementation, for all the reasons cited in the documentation.

    However, you don't have to implement Comparable to order instances of a value object class, and indeed you probably shouldn't if you intend to order them multiple ways. Simply passing an anonymous inline Comparator implementation to a sort method will suffice, with different comparator implementations for different orderings. This is easier than ever since Java 8 and lambdas. In recent years I myself have shied away from implementing Comparable for this very reason.

    Of course, if there really is a natural ordering for your specific value object class, then by all means implement Comparable. In that case make sure it is consistent with your equals() implementation.