mardi 27 juillet 2021

How do I avoid code duplication in my case?

I am currently working on code that converts one data model to another. More precisely, it is a Hafas model, but it is not very important. The problem is that I have to support multiple versions of this model. I currently have a converter for version 1.23 and version 1.29. Thousands of lines of code, about 50 methods that are 97% identical.

So I get XML with the data that I first need to deserialize to the POJO classes I constructed and then convert them with my algorithms.

The problem is that these versions use different packages of my POJO classes that have 99% same names.

Here is one example: Converter for 1.23 version:

public void convertHafasLegsInsideCustomTrip(TripStructure myTrip, LegList hafasLegs) {
    for (Leg hafasLeg :
            hafasLegs.getLeg()
    ) {
        // We have to convert each Hafas Leg to Trias TripLegStructure
        TripLegStructure myTripLeg= convertToTriasTripLeg(hafasLeg);

        if (myTripLeg!= null)
            myTrip.getTripLeg().add(myTripLeg);
        else
            throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
    }
}

Converter for V1.29:

public void convertHafasLegsInsideCustomTrip(TripStructure myTrip, LegList hafasLegs) {
    for (Leg hafasLeg :
            hafasLegs.getLeg()
    ) {
        // We have to convert each Hafas Leg to Trias TripLegStructure
        TripLegStructure myTripLeg= convertToTriasTripLeg(hafasLeg);

        if (myTripLeg!= null)
            myTrip.getTripLeg().add(myTripLeg);
        else
            throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
    }
}

The problem is that the LegList and Leg inside packages are different. So in the first case, they are imported from the generated POJO classes for version 1.23 and in the second example from the POJO classes for version 1.29.

The algorithm that converts is almost identical and I have many other methods that are 100% identical, only a few of them are different because some classes have different names in these two packages.

My next problem is that I may later implement a converter for another version that will also have similar features and I don't want to duplicate the code for each of them.

Aucun commentaire:

Enregistrer un commentaire