I think this is a very common situation in web projects. Assume there is an entity such as:
//JAVA code
@Data
class Entity{
private String a;
private String aExt;
private String b;
private String bExt;
private String c;
private String cExt;
... something more ...
}
For some purpose, I need to get part of values from Entity
according to a passed argument, like:
public ViewObject foo(Entity entity, String condition){
ViewObject vo = new ViewObject();
if("aRelated".equals(condition)){
vo.setValue1(entity.getA());
vo.setValue2(entity.getAExt());
}
else if("bRelated".equals(condition)){
vo.setValue1(entity.getB());
vo.setValue2(entity.getBExt());
}
else if(cRelated".equals(condition)){
vo.setValue1(entity.getC());
vo.setValue2(entity.getCExt());
}
... else statement if there are other values ....
return vo;
}
I know I can use switch-case
statement to reduce some words in foo()
, but there is no essential difference compared with if-else
, especially when the Entity
has many variables.
As a plain Example, foo()
is only a view object builder, but my project is more complex which have many duplicated code with only different variable's name in each if-else
statement.
How do I reduce the above duplicated code?