HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Transformation of abstract models

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
transformationabstractmodels

Problem

In one of my recent projects I faced the problem of transforming an abstract class into another abstract class. The classes were structured like this and are part of an api for questionnaires:

abstract class AnswerConstraint { /* shared implementation for all entities */ }

class LengthConstraint extends AnswerConstraint { /* specific members for this entity */ }
class RangeConstraint extends AnswerConstraint { /* specific members for this entity     */ }

abstract class AnswerConstraintResource { /* base class for serializable entities */ }

class LengthConstraintResource extends AnswerConstraintResource { /* includes members of LengthConstraint that should be serialized */ }
class RangeConstraintResource extends AnswerConstraintResource { /* includes members of RangeConstraint that should be serialized */ }


In my business logic, I only have to deal with the basetype of the entity, but as soon as the entites need to be serialized, I first need to transform them into the according resource entity.

My thoughts were:

  • Create an abstract method in AnswerConstraint for transformation



I do not like this approach because why should my entity deal with serialization classes of the weblayer?

  • Use instanceof to determine concrete type



I do not like this approach because it is not flexible and not object-oriented in any way.

I finally came up with the following solution and would like to hear your opinions about it.

public interface TransformStrategy {
    public T transform(S model);
    boolean canTransform(Class clazz);
}

public abstract class AbstractTransformStrategy implements TransformStrategy {

    private final Class sourceClass;

    public AbstractTransformStrategy(Class sourceClass) {
        this.sourceClass = sourceClass;
    }

    @Override
    public boolean canTransform(Class clazz) {
        return sourceClass.equals(clazz);
    }
}


The AbstractTransformStrategy serves as a base class for all TransformStrategys. Note th

Solution

To me it looks like you are reinventing the wheel.

Several mapping frameworks exist that not only support complex mappings between two similar objects, but also programmatic transformations. For example, you should consider:

  • ModelMapper - see Custom Converters in ModelMapper



  • Dozer. - see Custom Converters in Dozer.

Context

StackExchange Code Review Q#67449, answer score: 2

Revisions (0)

No revisions yet.