I have a need to do some processing from a format A to a format B and from B to A. The job in one direction is very similar to its counterpart. Both formats are represented with an interface Msg
.
In such a case, I can see four obvious solutions, which is the cleanest? I hope there are some concrete principles explaining one choice over the others and not just personal preferences
Here are the obvious choices
1) Different classes for each
public class TransformToA {
public TransformToA() {
...
}
public Msg transform(Msg incoming) {
...
}
}
public class TransformToB {
public TransformToB() {
...
}
public Msg transform(Msg incoming) {
...
}
}
Note that in this option, I could extract some common logic into a third common class to avoid code duplication
2) A boolean field to define the direction
public class Transformer {
private boolean toBFormat;
public Transformer(boolean toBFormat) {
...
}
public Msg transform(Msg incoming) {
if (toBFormat) {
...
} else {
//to A format
}
}
}
3) a boolean flag on the method (this is probably the worst since the caller is forced to pass the flag every single time and makes a method behave in two different ways)
public class Transformer {
public Transformer() {
...
}
public Msg transform(Msg incoming, boolean toBFormat) {
if (toBFormat) {
...
} else {
//to A format
}
}
}
4) Two different methods
public class Transformer {
public Transformer() {
...
}
public Msg transformToA(Msg incoming) {
...
}
public Msg transformToB(Msg incoming) {
...
}
}