简体   繁体   中英

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:

  • return a String
  • throw an exception

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?

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.

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.

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

您可以返回差异对象列表或字符串列表,其中每个项目代表一个差异。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM