I'm trying to map a dataset(let's call it Set1) onto another(Set2). The mapping is done by applying an operation to a subset of Set1 and placing the result to an object of Set2. I would like to know how can I structure the classes in an efficient and elegant manner (trying to learn OOP). Code below is working but the initialization order and content of classes is kindof awkward.
interface Operator{
public void transform(List<String> from, Element to);
}
class Transform{
public List<String> fromIndex;
public Integer toIndex;
Operator op;
Mapper m;//NICE TO NOT HAVE ref to Mapper
Transform(List<String> fromIndex, Integer toIndex, Operator op, Mapper m){
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.op = op;
this.m = m;
}
public void execute(){
List<String> from = new ArrayList<String>();
Element to = m.Set2.get(toIndex);
for(String s : fromIndex){
from.add(m.Set1.get(s));
}
op.transform(from,to);
}
}
class Mapper{
Map<String,String> Set1;
Map<Integer,Element> Set2;
List<Transform> transforms;
Mapper(Map<String,String> Set1, Map<Integer,Element> Set2){
this.Set1= Set1;
this.Set2= Set2;
}
public void setTransforms(List<Transform> transforms){
this.transforms = transforms;
}
public void doMapping(){
for(Transform t: transforms){
t.execute();
}
}
}
Typical usage scenario, assuming Set1 and Set2 are already filled (Set2 is filled with Elements whose values will be updated):
List<Transform> tList = new ArrayList<Transform>();
Mapper m = new Mapper(Set1,Set2);
tList.add(new Transform(new ArrayList<String>(Arrays.asList("3", "3_")),3,concatStringToInteger,m));
tList.add(new Transform(new ArrayList<String>(Arrays.asList("4", "4_")),4,concatStringToInteger,m));
tList.add(new Transform(new ArrayList<String>(Arrays.asList("22")),22,concatStringToInteger,m));
tList.add(new Transform(new ArrayList<String>(Arrays.asList("24")),24,concatStringToInteger,m));
m.setTransforms(tList);
m.doMapping();
The operators are just some reusable lamba exp. As you can see, Transform needs to hold a ref to mapper and the whole initialization is awkward. This is not a question about functionality (so please ignore any code errors, the code works) but about structuring this in an OOP (and maintaining a degree of generality) manner. Thanks
Aucun commentaire:
Enregistrer un commentaire