-1

Do i have any advantage while using functional style in my below example case

I have a below method

 public static String someMethod(String source) {
     //some operation
     return source;
 }

I changed above method to below style.

public static Function<String,String> process = source -> {
      //some operation
      return source;
   }

What are the advantages do i get for above change including performance at run time?

Pavan
  • 103
  • 1
  • 6
  • 3
    You'd need to define what you consider an advantage... Perfomance, readability, reusability, maintainability, compile time..... – Nicktar Dec 16 '19 at 06:58
  • 7
    This isn't really an example of using the functional style. If you want to use a static method as a `Function` then you can refer to it by a method reference like `MyClass::process`. The functional style is in the code which makes use of the method as a `Function` rather than merely calling it imperatively. – kaya3 Dec 16 '19 at 06:58
  • It depends where you use this... For example, `list.stream().map(process)` vs `list.stream.map(Foo::someMethod)`. – OneCricketeer Dec 16 '19 at 07:00
  • @Nicktar advantage in performance, Is there any performance impact while using them in other methods. we are calling them like below. SomeUtilClass.process.apply("string"); – Pavan Dec 16 '19 at 07:03
  • @kaya3 : we are calling them in some other methods like SomeUtilClass.process.apply("string"); not in any streams. – Pavan Dec 16 '19 at 07:07
  • Then you are writing in the imperative style. – kaya3 Dec 16 '19 at 07:07

1 Answers1

1

Using Function does not make your code functional.

The difference here is that in the first case you invoke the code immediately in the current context, and in the second case you return something that allows you to invoke the code later on something that do not need to be present now.

This is what Lambda expressions are for - a concise syntax for defining code snippets to be invoked later.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • Yes! but i wanted to know is there any performance impact at run time while using latter approach than static method. We aren't passing them to streams we just used another methods. – Pavan Dec 16 '19 at 07:10
  • 1
    To my understanding there is no more performance impact than for any other set of similar method calls. If this is really important to you, then don't blindly rely on the advice on strangers but actually measure yourself. – Thorbjørn Ravn Andersen Dec 16 '19 at 07:15