Home > database >  Replacing multiple methods with single methods using functional programming
Replacing multiple methods with single methods using functional programming

Time:01-12

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

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?

CodePudding user response:

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);

CodePudding user response:

The docs sugest making a class that implements runnable.

class TestClass {
    class anotherRoutine2 implements runnable{
      void run(){
          //some code logic
      }
    }

    void someOtherRoutine2 implements runnable{
      void run(){
          //some code logic
      }
    }

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

      public static void main(String[] args) {
      TestClass object1 = new TestClass();
      object1.newMethod(new object1.anotherRoutine2());
      object1.newMethod(new object1.someOtherRoutine2());
    }
}
  •  Tags:  
  • Related