Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing multiple methods with single methods using functional programming

I have a code with routines like this (the actual code base is pretty extensive but I am presenting a minimal version for explaining it)

class TestClass {
    void anotherRoutine2(){
      //some code logic
    }
    
    void someOtherRoutine2(){
      //some code logic
    }
    
    void method1() {
      routine1();
      anotherRoutine2();
      routine3();
    }

    void method2() {
      routine1();
      someOtherRoutine2();
      routine3();
    }

    public static void main(String[] args) {
      TestClass object1 = new TestClass();
      object1.method1();
      object1.method2();
    }
}

so we can see that the only way method1 and method2 differs is method1 is calling anotherRoutine2 whereas method2 is calling someOtherRoutine2.

I am trying to use functional programming in this scenario whereby I want to combine method1 and method2 in such a way that the routines which are changed is passed as argument. So I am planning to do the following

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class TestClass {
    void anotherRoutine2(){
      //some code logic
    }
    
    void someOtherRoutine2(){
      //some code logic
    }

    void newMethod(Runnable methodName) {
      routine1();
      methodName.run();
      routine3();
    }

    public static void main(String[] args) {
      TestClass object1 = new TestClass();
      object1.method1(()->object1.anotherRoutine2());
      object1.method2(()->object1.someOtherRoutine2());
    }
}

Is there a better way to solve this?

>Solution :

You have a few typos (should be newMethod) but you can do it that way. Or use a method reference as follows:

TestClass object1 = new TestClass();
object1.newMethod(object1::anotherRoutine2);
object1.newMethod(object1::someOtherRoutine2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading