After you’ve read in Part 0 why functional programming is cool, we will make our first big steps into this topic today. In Java 8, functions became first class. Therefore, you can take functions as arguments of other functions, return functions and store functions as objects.
Why should you store a function as an object?
1. Make “super private” functions
As you know, code quality is important. That’s the reason we use private functions to reduce the methods one object of a class has. We don’t want to show the underlying code to others, they just have to work with some public methods on the object. But what if we want to create functions in our class which are visible to just one method and invisble to the rest of the class? With functions as first class objects, We can store the function in a single object, which can be seen just in this very one method.
2. Upgrade Design Patterns
If you ever worked with on a big software project you know how messy it can become. That’s the reason design patterns were invented. One of the cooler ones is the Strategy Pattern. I will write a detailed post about it later on, but what it basically does is to switch similar algorithms, depending on a parameter. For each algorithm, you have to write your own class, which implements a function from an interface. But when you can store functions in an object, you just need one “function object” for each algorithm. That makes the code much clearer and smaller.
3. Create “higher-order” functions
Now comes the fun part. You can use every object as a parameter of a method. So why not call a method with a function argument? Methods which take a function as a parameter or return one, are called higher-order functions. Before I can give you an example we have to learn how to store a function in an object.
Storing a function in an Object
In Java 8, the java.util.Function
Example: compute function
This is a very easy example of a higher-order function. It takes a function and an Integer and computes the given function with the Integer.
How to work with Lambdas
To work with Lambdas in Java 8, we have to look at a new syntax to handle them properly.
Example: Adding Two Integers
In good old Java 7, you can write a method to add two Integers like this:
That’s it for today! We have made our first big steps towards functional programming in Java 8. First off, we have seen a lot of benefits of fP. After that, we have used our first function as an argument in another method by using method references and Lambdas (anonymous functions). In part 2, we will introduce Optionals and how we can work with them properly.
* An Introduction to Functional Programming in Java 8: Part 2 - Optionals
* An Introduction to Functional Programming in Java 8: Part 3 - Streams