tags:

views:

58

answers:

1

Hi All,

I have an interface and two objects implementing that interface, massively simplied;

public interface MyInterface {
    public int getId();
    public int getName();
    ...
}

public class A implements MyInterface {
    ...
}

public class B implements MyInterface {
    ...
}

We are migrating from using one implementation to the other but I need to check that the objects of type B that are generated are equivalent to those of type A. Specifically I mean that for all of the interface methods an object of Type A and Type B will return the same value (I'm just checking my code for generating this objects is correct).

How would you go about this?

Map<String, MyInterface> oldGeneratedObjects = getOldGeneratedObjects();
Map<String, MyInterface> newGeneratedObjects = getNewGeneratedObjects();

// TODO: Establish that for each Key the Values in the two maps return equivalent values.

I'm looking for good coding practices and style here. I appreciate that I could just iterate through one key set pulling out both objects which should be equivalent and then just call all the methods and compare, I'm just thinking there may be a cleaner, more extensible way and I'm interested to learn what options there might be.

Would it be appropriate / possible / advised to override equals or implement Comparable?

Thanks in advance,

Gavin

+2  A: 

I would implement a custom version of equals in the test class, not inside any of those implementation classes (since it would clash with the regular equals contract). Something like:

boolean equals(A a, B b) ...

I understand that this check would be required only during the migration period, so the normal equals methods of each implementation should not be affected by this. Namely, A.equals should only return true for an equal instance of A, and should always return false for an instance of B. And vice versa.

Once the migration is over, you no longer need class A neither the tester class, and you can continue using class B without needing to touch its implementation.

Note that if MyInterface (or A and B) extends Comparable, you should also test that the implementations in A and B are equivalent.

(And you surely know that if you implement equals you must also implement hashCode.)

Péter Török
Fantastic, this makes sense to me, I'll write the code as a test and keep the implementations out of the equation.You're right that this code will only be used during the migration.
gav