Transformations between Domain Models, OOP fails, no such Design Pattern

The issue:
There are 3 (three) Domain Models (Object hierarchies, groups of objects). They are parts of different tiers of an application. Their hierarchy trees are nearly the same.
Why we have three DM is another issue, but is not in the focus of the following discussion.

The task is to convert objects from one Domain Model to another. As I said, the objects are nearly the same, data objects, no logic.

Until now there were static methods that do that. It's ugly - there's another class, inheritance is impossible - logic has to be extracted like this

public static M2Object convertM1toM2(M1Object) { /* logic */ }

becomes

public static M2Object convertM1toM2(M1Object m1) { convertM1toM2(m1, result); }

private static void convertM1toM2(M1Object m1, M2Object m2) { /* logic */ }

because the result is now an inheriting class and cannot reuse M2Object convertM1toM2(M1Object), but can reuse void convertM1toM2(M1Object m1, M2Object m2).

What I proposed was to put converters in one of the Domain Models, M2 was chosen.
so now M2 has

new M2Object(M1Object)
new M2Object(M3Object)

M1Object toM1()
M3Object toM3()

Inheritance with constructors is working smoothly. The problem comes from the toXXX() methods. Inheritance is difficult because the super toXXX() creates the result (base M1/M3 class), but the result in inheriting toXXX() method should be inherited M1/M3 class.

So now I'm thinking of (M2InheritedObject):
protected final void convertTo(M1InheritedObject m1) {
   super.convertTo(m1);   // convert base class properties (reuse happens here)
   /* +extra logic */     // convert inherited class properties
}
public M1InheritedObject toM1() {
       
M1InheritedObject result = new M1InheritedObject();
        this.convertTo(result);
        return result;
}

This method is gonna be reused, inheritance is weird  - this is actually kinda unclean, but the best I can think of.

I'm thinking of some design pattern, (Adapter for example), but that good for objects, not object hierarchies.

If somebody thinks of something, I'd appreciate it.

3 thoughts on “Transformations between Domain Models, OOP fails, no such Design Pattern”

Leave a Reply

Your email address will not be published.

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.