Random42
Random42

Reputation: 9159

How to return the comparison differences when comparing two complex objects?

I have to compare two complex objects which are of different types (and do not have a common superclass in the type hierarchy) but logically they may be equivalent. The problem is on how to return the information about the result of the comparison in case the objects are not equal; I would like to inform the caller why the objects are not equals (what fields are different and how are they different).

The options thus far are:

but I do not find them very elegant/good.

Also, is there a way to delegate the field comparisons to assertEquals from JUnit and thus base my comparison on JUnit without the comparison test to be an actual unit test?

Upvotes: 1

Views: 1035

Answers (4)

aioobe
aioobe

Reputation: 420971

If the comparison is complex, the result of the comparison is (as you mention) potentially complex.

I therefore recommend you to consider a third option: Create a custom class, ComparisonResult that encapsulates the information of the result.

You could even create a little hierarchy, and rely on polymorphism to simplify the code. Here's an example:

ComparisonResult
|
+--- Equals
|
+--- Not equals
     |
     +--- Compatible (with "isAbeforeB()")
     |
     +--- Incompatible (with "getReason()")

The Incompatible is presumably the messiest class, which I suggest you implement by a list of reasons why the objects are incompatible. A reason could perhaps itself be an abstract class, with subclasses such as MissingField etc.

Upvotes: 4

You can return a list of Difference objects or a list of string where each item wold represent one difference.

Upvotes: 0

leifg
leifg

Reputation: 8988

The equals method should only return a boolean (equal or not).

You should not mix the functionality of comparison and getting the difference.

For your purpose it makes sense to implement an additional method (a.getDifferences(b) or static method Comparision.getDifferences(a,b) if you don't have a common superclass (besides object))

For the implementation of the equals it makes sense to call the getDifferences method and check if the returned object is empty.

The result could then be a string or a separate object

Upvotes: 0

Miquel
Miquel

Reputation: 15675

Careful! If your comparison implementation does not match equals, you might get in trouble when using that object in different container implementations.

That said, the comparison interface can only return int, so you'd have to come up with a different method that does not impement Comparable.

Upvotes: 0

Related Questions