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) {
...
}
}
A
it will produce aB
and vice versa.doSomething(true)
, the boolean tells me nothing at face value. Anyways, why not establish a common intermediate format and then give each message type the ability to translate its contents to and from that format? It avoids an explosion of combinations and lets you look at private fields if needed.