Search code examples
javafunctional-programmingabstraction

Java : Using Functional Vs OOP Paradigms


I Have a specific behaviour which i want to abstract out in my class.

I See two ways how i can do this.

Option 1 : The behaviour can be overridden by the conventional subclassing of 'SomeClass'.

Class SomeCalss{
  public Output behaviour(Input){
    //overriden behaviour
  }
}

Class SomeOtherClass extends SomeCalss{
  public Output behaviour(Input){
    //overriden behaviour
  }
}

Option 2 : The behaviour can be specified by Plugging in the functional definition from outside

Class SomeCalss{
  public Output behaviour(Function<Input,Output> function, Input){
    //Functional paradigm
  }
}

No Subclassing is needed in 'Option 2'.

Question : (Edit)

  • With java now fully supporting these paradigms of functional programming from java8+ onwards, has there been any shift in the conventional process to abstract out behaviours. What is the better way of abstracting out my behaviour, and why ? Incase the same is case to case dependent, what are the cases when 1 should be used over the other ?.

Solution

  • While Option 2 gives you flexibility, it forces client code to specify the Function argument, which you will probably want to avoid.

    Your goal is to provide clients with a simple interface (behaviour(input)) and hide everything you can- so that clients stay independent from your code.

    Option 3 would be

    interface Behaves { public Output behaviour(Input i); }
    class Behaviour1 implements Behaves {
      public Output behaviour(Input i){ /* your implementation here*/ }
    }
    class FunctionBasedBehaviour implements Behaves {
      private final Function<Input,Output> f;
      public FunctionBasedBehaviour (Function<Input,Output> f) {this.f=f;}
      public Output behaviour(Input i){  return f(i); }
    }