I have two similar pieces of Code:
void task1() { init(); while(someCondition) { doSomething(); } shutdown(); } void task2() { while(someCondition) { init(); doSomething(); shutdown(); } } I would like to avoid code duplication and I thought this could be done by using a functional approach. I want to put the loop and the init/shutdown call in seperate functions and then chain their calls (not the Java 8 Function interface, more pseudocode):
Function setup(Function f){ init(); f(); shutdown(); } Function loop(Function f){ while(someCondition) { f(); } } Then I want to chain these like this:
void task1() { setup(loop(doSomething)); } void task2() { loop(setup(doSomething)); } I thought of compose/andThen in Java's Function interface but they are not suitable because they only hand on the return value of one function to the next one. Does anyone have an idea how to do this with Java 8 or with a different approach?
init,doSomethingandshutdownare actual methods, there is no duplication.