0

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?

4

4 回答 4

2

Command pattern sounds fine here. But I would rather look for possibility of solving this with various value types, instead of using Object. So, I can simply write one-liner like below,

value.process()
于 2012-05-25T07:20:46.330 回答
1

What will happen if there is new type for processing. In first approach you will add case. In case in switch. If you use command pattern, you need to inject the new command and its type and its up and running. I will use Second approach any day

Also why you need to pass this? recurciveProcessing can be command which uses map to get the command to handle request?

于 2012-05-25T07:10:55.077 回答
1

I agree its always better to avoid switch case statement. So creating a command map would do. Another easier approach could be to add the process method inside your enum so that every enum type knows how to process the data.

于 2012-05-25T07:23:49.810 回答
0

There's nothing wrong with that switch block. The JVM has nice ways of dealing with it which don't impact on performance.

于 2012-05-25T07:07:28.500 回答