Functional programming in Java

Since we have created a lot of code in our example for this chapter, we will look at the functional programming features of Java, which will help us delete many lines from our code. The less code we have, the easier it is to maintain the application; thus, programmers love functional programming. But this is not the only reason why functional programming is so popular. It is also an excellent way to describe certain algorithms in a more readable and less error prone manner than conventional loops.

Functional programming is not a new thing. The mathematical background was developed for it in the 1930s. One of the first (if not the first) functional programming languages is LISP. It was developed in the 1950s and it is still in use, so much that there is a version of the language implemented on the JVM (Clojure).

Functional programming, in short, means that we express the program structure in terms of functions. In this meaning, we should think of functions as in mathematics and not as the term is used in programming languages such as C. In Java, we have methods, and when we are following the functional programming paradigm, we create and use methods that behave like mathematical functions. A method is functional if it gives the same result no matter how many times we invoke it, just as sin(0) is always zero. Functional programming avoids changing the state of objects, and because the state is not changing, the results are always the same. This also eases debugging.

If a function has once returned a certain value for the given arguments, it will always return the same value. We can also read the code as a declaration of the calculation more than as commands that are executed one after the other. If the execution order is not important, then the readability of the code may also increase.

Java helps functional programming style with lambda expressions and streams. Note that these streams are not I/O streams and do not really have any relation to those.

We will first take a short look at lambda expressions and what streams are, and then, we will convert some parts of our program to use these programming constructs. We will also see how much more readable these codes become.

Readability is a debatable topic. A code may be readable to one developer and may be less readable to another. It very much depends on what they got used to. I experience many times that developers get distracted with streams. When developers first meet streams, the way to think about them and how they look is just strange. But this is the same as starting to learn using a bicycle. While you are still learning its use and you fall more than you roll, it is definitely slower than walking. On the other hand, once you have learnt how to ride a bike...

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.184