This Month I want to talk about functional programming, especially understanding functional programming using Java 8. This will be a two part series where part one covers introduction to functional programming and part two covers handling exception as values. i.e. Handling Exception in Functional approach.

Java 8’s lambdas (λ) empower us to create great API’s using functional paradigm.  Functional Programming principles make’s our code more reusable, elegant, clean and bug free.  I’m gonna use this short representation for Function Programming(FP) word from now on. I want to share my thoughts on FP like, why Should you care about it, what are the basic principles and how we can implement it in Java 8. Please be prepared, You will have to think like a beginner one more time for Understanding Functional Programming principles.  Let’s start with a very basic question…….

What is Functional Programming ?

We develop our programs using only pure functions. i.e. Functions that have no side effects. So, What are side effects ? A function has side effect if it does something other than simply return a result.

Example :

  • Modifying a Variable
  • Modifying a data structure in place
  • Setting a field on an object
  • Throwing an exception or halting with an error

Is this possible ? How is even possible to write useful programs at all If we can’t reassign a variables, how do we write simple programs like loops or handling errors without throwing exceptions ?

Note : However, real-world applications do perform side-effects.

Example of a Side-effect function.

https://gist.github.com/kishorenayar/b5c455f6627c5a470388

I know it is difficult to write programs without loops or modifying variable, That’s why we need to understand the ground principles of Functional Programming. I don’t want to talk more about FP in theory but I  want to explain in a simple way. So to understand FP, You need to know about Immutable values and Referential Transparency.

Note : The key to a functional paradigm is to use immutable values paired with referential transparent functions.

Immutable values

One which you cannot change once you created it. It is important that you use immutability whenever possible. Think in immutable and reduce mutability state. A very good simple example of immutability in Java is String class. String’s are immutable by default.

Referential Transparency

A function,  is called referential transparent if a call can be replaced by its value without affecting the behavior of the program.

Example:

https://gist.github.com/kishorenayar/adee4448641cd2b554eb

What can we gain from Functional Paradigm ?

Functional programming is tremendously beneficial because of the increase in modularity that we gain from programming with pure functions. Because of this modularity, pure functions are easy to reuse, parallelize, generalize, test, etc.

Before seeing FP in practice, we also need to understand about lambda.

What is Lambda(λ) in Java?

Lambda is a new feature introduced in Java 8 making Java’s first step into functional programming. The Lambda’s are written as expression in the code which is basically an anonymous function. Simply put, it’s a method without a declaration, i.e., access modifier, return value declaration, and name. A lambda expression can be passed around as if it was an object and executed on demand. Please look into the reference sections for more detailed understanding.

I believe I gave a quick short intuition about FP in theory. Now Let’s apply these intuitions in a real world example.

Problem:

This is Project Euler first problem

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Let’s see how this can be done without applying loops.

https://gist.github.com/kishorenayar/aefe5ec644659068d307

Filter:

Useful for checking if an input argument satisfies some condition. The filter method accepts Predicate<T> which Represents a predicate (boolean-valued function) of one argument.

boolean test(T t)

Evaluates this predicate on the given argument.

Reduce:

In functional programming, reduce refers to a family of higher-order functions that analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value. In essence, reduce takes data in one format and gives it back to you in another.

https://gist.github.com/kishorenayar/ad66616d32a388b985a5

Let’s analyse the above function.

Interface BiFunction<T,U,R> – functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Type Parameters:
T – the type of the first argument to the function
U – the type of the second argument to the function
R – the type of the result of the function

Represents a function that accepts two arguments and produces a result.

It has this method which takes two parameter and returns you a new value.

R apply(T t, U u)

For quick reference visit BiFunction

Let’s have some fun with this function. Suppose you have list of numbers and you want to sum these numbers. The basic way of doing this applying for loop.

https://gist.github.com/kishorenayar/e64402873cb95571d292

Now Let’ s see how we can achieve the same in reduce in one line.

https://gist.github.com/kishorenayar/0dd5b4b4be35323e363b

WOW, It’s amazing Isn’t it. Without writing loops I was able to compute sum of values. This is very simple example of what reduce can do.

Similarly there are plenty of functional methods available in Java 8.

Note:

If You look into deeper level, You can understand that the functional programming is not a world without side effects or mutability, but one where we don’t have to directly deal with them.

Essential Practices for Writing FP

  • Favor Immutability
  • Reduce Side Effects
  • Prefer Expressions Over Statements
  • Design with Higher-Order Functions
  • More Declarative, Less Imperative

Caveat:

Beware, Lambda’s can make your code slower some times. This is because Java is designed with OOPS and the byte code which getting generated from java is based on OOPS. There is good blog about these caveats. Sometimes it’s preferred to use iterators and loops when you want hardcore performance.

Problems

Now It’s Your turn, Following is the list of problems where you can try to solve using FP paradigm

  • Compute the product of a List using reduce
  • Concat two list into one using reduce
  • Convert String of numbers to Int using map function
  • Compute WordCount of a given file with out using for loop.

Don’t worry If you are not able to solve the above problem. Here is solutions for the above problems.

https://gist.github.com/kishorenayar/3e52061e69eaf57a7f6f

I hope I gave you a basic idea of what Functional Programming is. In the next series I will write about handling exception in FP way. Stay Tuned……

References:

  1. Understanding Lambda in Java
  2. Lamba Expression in Java
  3. Lambda Introduction to Java