I have two classes which have identical behaviour, except class SnakeCaseyMapper uses snake_case constant fields and class CamelCaseyMapper uses camelCase constant fields.
Before requiring two of these classes, my logic looked roughly like:
public class Mapper {
public static final String FIELD = "snake_casey_field";
// Lots of other constant fields ...
public Foo map(Bar bar) {
// Some logic that makes use of the constant FIELDs
}
}
public class ClassThatsDoingLogic {
var mapper = new Mapper();
var result = mapper.map(bar);
}
Now I require this same method, map(Bar bar) but with camelCase constants, as well as the original implementation with snake_case.
My idea was to make use of abstract classes:
public abstract class Mapper {
public String field; // Not instantiated here
// Lots of other member variable fields ...
public Foo map(Bar bar) {
// Some logic that makes use of the constant FIELDs
}
}
public class SnakeCaseyMapper extends Mapper {
public SnakeCaseyMapper() {
field = "snake_casey_field";
// Lots of other fields instantiated
}
}
public class CamelCaseyMapper extends Mapper {
public CamelCaseyMapper() {
field = "camelCaseyField";
// Lots of other fields instantiated
}
}
public class ClassThatsDoingLogic {
var snakeCaseyMapper = new SnakeCaseyMapper();
var result = snakeCaseyMapper.map(snakeCaseyBar);
var camelCaseyMapper = new CamelCaseyMapper();
var result = camelCaseyMapper.map(camelCaseyBar);
}
This way both classes use the same method logic in map() without duplicating the code. However, I think I lose the finality of the constant fields I had originally. Is there a way around this? Is there a way of handling this problem I'm missing?