Shorten The Code Lengenthen the fun with The Functional Interface in java…
The Function Interface is part of the “java.util.function” package that has been introduced since Java 8 to implement functional programming in Java. It represents a function that takes in one argument and produces a result. Hence this functional interface takes in 2 generics namely as follows:
T: denotes the type of the input argument
R: denotes the return type of the function
Functional interfaces provide target types for lambda expressions and method references. As Java 8 brought a powerful new syntactic improvement in the form of lambda expressions. A lambda is an anonymous function that we can handle as first-class language citizens.
For instance, we can pass it to or return it from a method. Before Java 8, we would usually create a class for every case where we needed to encapsulate a single piece of functionality. That implied a lot of unnecessary boilerplate code to define something that served as a primitive function representation.
Functional Interface In Java works by cutting out the unnecessary code from your lengthy code. The use case of functional interface could result in better code optimization. The shorter length of the code results in easier debugging of the code and there is very less chance of the bugs being present in the code.
Take the below psuedo code of Functional Interface approach in java:
In Fig 1, ClassB is working as the mediator between classC and ClaasA. It is taking the request from classA and sending it to the classC. But the same code can be rewritten or shortened using the functional interface as shown below in Fig 2.
Now, in Fig 2, We can see that the size of classB has been shortened remarkably. In Fig 2 we have replaced the different methods with just one method, and an additional argument as a function that takes an integer and returns a string and an integer that was taken earlier and it will call the uplime function of the method.
As the classB signature is changed we also changed classA. As when classB method is called ClaasA will also pass the corresponding method of classC, which needs to be called and classB will call the method of classC as earlier.
For a Better understanding of Functional Interface In Java refer to the youtube video
Reference Code links:
[…] In Fig 1, ClassB is working as the mediator between classC and ClaasA. It is taking the request from classA and sending it to the classC. But the same code can be rewritten or shortened using the functional interface as shown below in Fig 2. […]