Search This Blog

Wednesday 19 August 2015

Lambda

This is kind of late - very late, but then like always - better late than never. So while java lovers world over have dug deep, praised, criticized and in some cases confused the developer community about Lambda expressions in Java 8, I have finally woken and decided to throw my two cents into the pit.
I was kinda too busy/lazy until I got a code review that used Lambdas. With no escape but to review it, I had to start learning Lambdas.  This post is a collection of thoughts I found online and like always just my ready notes to be available for me to refer back when the next code review comes around. With that time to get started.....
Am sure we all had an use case, where we needed a list sorted. Being a one off, writing a top level comparator class and using it seemed an overkill. So we turned to anonymous classes.
public void someMethod() {
      List<User> users = getListOfUsers();// some complex code
      //Need to sort this List by age ofusers
      users.sort(new Comparator<User>() {

         @Override
         public int compare(User u1, User u2) {
            return Integer.compare(u1.getAge(), u2.getAge());
         }
      });
      //Continue processing the sorted list
   }
I guess other than the UI cases, this is one of the popular areas we see anonymous classes in code. This works. Perfectly. But the amount of code needed to say "compare users on age" is several lines. In production code you would even run across comments.
With Java 8, Oracle introduced the style of functional programming to Java. Before moving forward, I looked up the definition on wikipedia:
In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
Quite a lot to grasp at one go, so a some points of  note:
  1. Functional programming involves code that is stateless (Think of HTTP and REST)
  2. Functional programming works with immutable data.
Point 2 means that the function is kind of only working with the parameters that you passed to it.While 1 means that your function has no real recall of any operations it did before.

The compare method that we have above fits this paradigm. It only operates on the two parameters that we passed to it. Also it does not have any recall, i.e. it does not care of the results of an previous comparisons.
Accordingly Java 8 has changed the code for the Comparator interface:
@FunctionalInterface
public interface Comparator<T> {
As seen above a new annotation has been introduced to mark such interfaces ( have exactly one method and which satisfy the above two rules) as functional interfaces.
So we have heard about Functional  programming, seen java identify code that can be written in a functional manner and have them annotated as functional interface. But what is Lambda expression ?

Lambda Expressions are one of the ways to create instance of Functional Interface. From the Oracle tutorial, Lambda Expressions could be :
This is a really powerful thing - we are creating complex objects through expressions

Now that we have seen the various terms, time to rewrite our Comparator as a lambda expression:
public void someMethod() {
      List<User> users = getListOfUsers();// some complex code
      // Need to sort this List by age ofusers
      users.sort(Comparator.comparing(user -> user.getAge()));
      // Continue processing the sorted list
   }
As seen, the whole code has been written as a single line.
Thus our simple lambda expression which converts a user instance to a integer instance (user.getAge()) is converted by the compiler into a Function instance. And what we were doing before with about 5 -10 lines of code now become 1 -2 lines.
Like I said before Lambda expression is not the only way to achieve functional programming in java. They also have a technique called Method references.
For instance the above code could be rewritten as:

 users.sort(Comparator.comparing(User::getAge));

There is much more to Lambdas. Its presence in Collection Libraries, threading code, Predicates....I have just scraped the surface here.

With help from:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
http://www.smashingmagazine.com/2014/07/dont-be-scared-of-functional-programming/
http://howtodoinjava.com/2014/04/18/using-comparator-becomes-easier-with-lambda-expressions-java-8/ 

No comments:

Post a Comment