Functions revisited

Unlike object-oriented programs, those written in a functional way don't hold any mutable state. Instead, code is made up with functions that take arguments and return values. Because there is no internal state nor side-effects involved that can alter the execution, all functions are deterministic. This is a really good feature because it implies that different executions of the same function, with the same parameters, would produce the same outcome.

The following snippet illustrates a function that does not mutate any internal state:

public Integer add(Integer a, Integer b) {
return a + b;
}

The following is the same function written using Java's functional API:

public final BinaryOperator<Integer> add =
new BinaryOperator<Integer>() {

@Override
public Integer apply(Integer a, Integer b) {
return a + b;
}
};

The first example should be completely familiar to any Java developer; it follows the common syntax of a function that takes two integers as arguments and returns the sum of them. The second example, however, differs a bit from the traditional code we are used to. In this new version, the function is an object that counts as a value, and it can be assigned to a field. This is quite convenient in some scenarios because it can still be used as a function in some cases and in some others it can also be used as a return value, as an argument in a function or a field within a class.

One can argue that the first version of the function is more appropriated since it is shorter and does not require creating a new object. Well, it's true, but the fact that functions can also be objects enhances them with a bunch of new capabilities. Regarding code verbosity, it can be considerably reduced to a single line by using a lambda expression:

public final BinaryOperator<Integer> addLambda = (a, b) -> a + b;

In the next section, a possible solution to Reverse Polish Notation (RPN) kata is presented. We are going to use the power and expressiveness of functional programming, particularly the lambda notation, which becomes really handy when functions are required as arguments of some functions. Using lambdas makes our code very concise and elegant, increasing the readability.

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

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