Karim Harazin
Karim Harazin

Reputation: 1473

Design pattern for bi directional data format conversion

I work on a project that will deal with different data formats.

for example, suppose i have the following data formats:

formatA, formatB, formatC, ...

with the following classes.

formatA:

public class dataFormatA {

    private String data;

    public dataFormatA(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatB convertToDataFormatB() {
        return new dataFormatB(data);
    }

    public dataFormatC convertToDataFormatC() {
        return new dataFormatC(data);
    }

}

formatB:

public class dataFormatB {

    private String data;

    public dataFormatB(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatA convertToDataFormatA() {
        return new dataFormatA(data);
    }

    public dataFormatC convertToDataFormatC() {
        return new dataFormatC(data);
    }

}

formatC:

public class dataFormatC {

    private String data;

    public dataFormatC(String data) {
        this.data = data;
        // convertData(this.data);
    }

    public dataFormatA convertToDataFormatA() {
        return new dataFormatA(data);
    }

    public dataFormatB convertToDataFormatB() {
        return new dataFormatB(data);
    }
}

What is the best design pattern to make? currently, each class has a method to convert its data type to the rest of data formats classes. But this is not a good design as it violat the open close principle

Upvotes: 4

Views: 854

Answers (1)

9000
9000

Reputation: 40894

Can you devise one (or a very small number of) intermediate format(s)? Let's call such a format M; then you'll only need converters from each format to M, and from M to each format. Adding more formats becomes easy.

If you have a nontrivial and unique way of conversion between each pair of formats, you're stuck with having a full matrix.

You still don't need to keep the converters code inside the format class.

Instead, I'd create a common converter interface:

interface FormatConverter<SRC, DST> {
   DST convertFrom(SRC);
}

Now you can use any mechanism you like to implement this interface, likely by having a bunch of converter classes.

The converters may see certain non-public details of each format class via package-level visibility. Alternatively, they could be format's inner classes. OTOH this again creates a tight coupling between the format class and converters, so open-closed principle may be violated.

Upvotes: 1

Related Questions