简体   繁体   中英

Refactoring - Methods share the same code except for one function call

I have several methods in class Test which have the same code except one specific method call. Is there a possibility to merge these methods together (bellow into function foo) and call foo and tell it which method to call without doing a bigger switch or if/else statement? An important note is that foo is only called from inside the class Test (therefore foo is private) and the function foo itself calls different methods from one class Bar. Class Bar and Test are not in the same inheritance tree.

class Test {

    /* ... */

    private void foo("Parameter that specifies which method to call from class Bar")
    {
        /* merged code which was equal */

        Bar bar = new Bar();
        bar.whichMethod(); // Call the method (from Class Bar) specified in the Parameter

        /* merged code which was equal*/
    }

    /* ... */

}

Sure straight forward I'd add some kind of switch("which Method to call") statement. But is there a better way to do this?

You can pass the method to call as an argument. Let's assume that the method to call has the following signature:

private void m() {...}

You could write:

private void foo(Runnable methodToRun) {
    //...
    methodToRun.run();
    //...
}

and your various foo methods would be like:

private void foo1() { foo(new Runnable() { public void run() { someMethod(); } }); }

With Java 8 you could also pass a lambda or a method reference.

As assylias said, you can use Method References with Java 8.

public void testAdds() {
    doTest(this::addOne);
    doTest(this::addTwo);
}

private void doTest(Function<Integer,Integer> func) {
    System.out.println("Func(41) returns " + func.apply(41));
}

public int addOne(int num) {
    return  num + 1;
}

public int addTwo(int num) {
    return  num + 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM