I have code similar to following:
void processObjectRecursively(Object obj)
{
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field : fields)
{
FieldType type = FieldUtils.getType(field); // FieldType is enum
Object value = field.get(obj);
switch(type)
{
case A:
processObjectRecursively(value);
continue;
case LIST:
processList((List<?>)value);
continue;
case B:
processB(value);
continue;
case C:
processC(value);
continue;
}
}
}
void processList(List<?> list)
{
for(Object obj : list)
{
processObjectRecursively(obj);
}
}
void processB(Object obj)
{
// do something
}
void processC(Object obj)
{
// do something
}
Now. I don't like this long switch case. So I'm thinking of creating commands and populating a Map with them where the type is the key and the value is its corresponding command object. With this, the method would look something like:
void processObjectRecursively(Object obj)
{
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field : fields)
{
FieldType type = FieldUtils.getType(field); // FieldType is enum
Object value = field.get(obj);
Command command = commandMap.get(type);
command.execute(value, this); // 'this' needed for calling processObjectRecursively()
}
}
But for this I will need to create one interface and four more classes. So is this approach okay or is it over-engineered? Can you suggest any other simpler approach to achieve the same effect?