andy007
andy007

Reputation: 917

How refactor the method?

There is a given method. How can we refactor it?

public void foo(Factor o){
    if(o.matches(constant1)){
          method1(); 
    }else if(o.matches(constant2)){
          method2(); 
    }
    }else if(o.matches(constant3)){
          method3(); 
    }
    ....
}

Upvotes: 1

Views: 193

Answers (2)

Kirkland
Kirkland

Reputation: 3267

This is something called a code smell. You would want to use what's called the "command pattern" which is a design pattern to refactor this code. On mobile now, will update with an example when I get to my desk today.

Edit: Here we go.

So the command pattern is a design pattern used for this exact scenario. What you need to first do is create a command Interface.

public interface MyCommand {
    public void execute();
}

Great. Next you create Command objects that hold all of your method data.

public class Method1Command implements MyCommand {
    public MyVariable var;

    public Method1Command(<your arguments to create method>)
    {
        // instantiate your command
    }

    public void execute()
    {
        // what your current method1() is;
    }
}

And then you just create some kind of private class in your Main to create a HashMap of all of the commands, keyed with the value of "ConstantX."

private static Map<String, MyCommand> getMyCommands()
{
    Map<String, MyCommand> commandList = new HashMap<String, MyCommand>();
    MyCommand c;

    c = new Method1Command();
    commandList.put("constant1", c);

    c = new Method2Command();
    commandList.put("constant2", c);

    c = new Method3Command();
    commandList.put("constant3", c);

    return commandList();
}

Then, in the refactored method you would simply do the following:

public void foo(Factor o)
{
    cl.get(o).execute();
}

This, however, assumes that o has some kind of toString method inside it, or if you have some method inside of o that you use to get the command it would be something like this: cl.get(o.getMyCommand()).execute();

Upvotes: 2

Maroun
Maroun

Reputation: 95948

You can make an array containing the constants, and a Map containing constant-string pairs (String is the name of the method), use reflection and do something like:

public void foo(Factor o) {
    for(int i = 0; i < constans.length; i++) {
        if(o.matches(constant)) {
            Method method = 
               YourClass.class.getMethod(myMap.get(constant), null);

            method.invoke(null);
        }
    }
}

Upvotes: 1

Related Questions