Programación funcional en Java

1. Introducción

En este tutorial, comprenderemos los principios básicos del paradigma de programación funcional y cómo practicarlos en el lenguaje de programación Java. También cubriremos algunas de las técnicas avanzadas de programación funcional.

Esto también nos permitirá evaluar los beneficios que obtenemos de la programación funcional, especialmente en Java.

2. ¿Qué es la programación funcional?

Básicamente, la programación funcional es un estilo de escribir programas de computadora que tratan los cálculos como si fueran funciones matemáticas de evaluación . Entonces, ¿qué es una función en matemáticas?

Una función es una expresión que relaciona un conjunto de entrada con un conjunto de salida.

Es importante destacar que la salida de una función depende solo de su entrada. Más interesante aún, podemos componer dos o más funciones juntas para obtener una nueva función.

2.1. Cálculo lambda

Para comprender por qué estas definiciones y propiedades de las funciones matemáticas son importantes en la programación, tendremos que retroceder un poco en el tiempo. En la década de 1930, el matemático Alonzo Chruch desarrolló un sistema formal para expresar cálculos basados ​​en la abstracción de funciones . Este modelo universal de computación llegó a conocerse como el cálculo Lambda.

El cálculo lambda tuvo un impacto tremendo en el desarrollo de la teoría de los lenguajes de programación, particularmente los lenguajes de programación funcionales. Normalmente, los lenguajes de programación funcionales implementan el cálculo lambda.

Como el cálculo lambda se centra en la composición de funciones, los lenguajes de programación funcional proporcionan formas expresivas de componer software en la composición de funciones.

2.2. Categorización de paradigmas de programación

Por supuesto, la programación funcional no es el único estilo de programación en la práctica. En términos generales, los estilos de programación se pueden clasificar en paradigmas de programación imperativos y declarativos:

El enfoque imperativo define un programa como una secuencia de declaraciones que cambian el estado del programa hasta que alcanza el estado final. La programación procedimental es un tipo de programación imperativa en la que construimos programas utilizando procedimientos o subrutinas. Uno de los paradigmas de programación más populares conocido como programación orientada a objetos (OOP) amplía los conceptos de programación procedimental.

En contraste, el enfoque declarativo expresa la lógica de un cálculo sin describir su flujo de control en términos de una secuencia de declaraciones. En pocas palabras, el enfoque del enfoque declarativo es definir qué debe lograr el programa en lugar de cómo debe lograrlo. La programación funcional es un subconjunto de los lenguajes de programación declarativos.

Estas categorías tienen más subcategorías y la taxonomía se vuelve bastante compleja, pero no entraremos en eso en este tutorial.

2.3. Categorización de lenguajes de programación

¡Cualquier intento de categorizar formalmente los lenguajes de programación hoy en día es un esfuerzo académico en sí mismo! Sin embargo, intentaremos comprender cómo se dividen los lenguajes de programación en función de su soporte para la programación funcional para nuestros propósitos.

Los lenguajes funcionales puros, como Haskell, solo permiten programas funcionales puros.

Otros lenguajes, sin embargo, permiten programas tanto funcionales como de procedimiento y se consideran lenguajes funcionales impuros. Muchos lenguajes entran en esta categoría, incluidos Scala, Kotlin y Java.

Es importante comprender que la mayoría de los lenguajes de programación populares en la actualidad son lenguajes de propósito general y, por lo tanto, tienden a admitir múltiples paradigmas de programación.

3. Principios y conceptos fundamentales

Esta sección cubrirá algunos de los principios básicos de la programación funcional y cómo adoptarlos en Java. Tenga en cuenta que muchas de las características que usaremos no siempre han sido parte de Java, y es recomendable estar en Java 8 o posterior para ejercitar la programación funcional de manera efectiva .

3.1. Funciones de primera clase y de orden superior

Se dice que un lenguaje de programación tiene funciones de primera clase si trata las funciones como ciudadanos de primera clase. Básicamente, significa que las funciones pueden admitir todas las operaciones que normalmente están disponibles para otras entidades . Estos incluyen asignar funciones a variables, pasarlas como argumentos a otras funciones y devolverlas como valores de otras funciones.

Esta propiedad permite definir funciones de orden superior en la programación funcional. Las funciones de orden superior son capaces de recibir funciones como argumentos y devolver una función como resultado . Esto permite además varias técnicas en programación funcional como composición de funciones y curado.

Tradicionalmente, solo era posible pasar funciones en Java usando construcciones como interfaces funcionales o clases internas anónimas. Las interfaces funcionales tienen exactamente un método abstracto y también se conocen como interfaces de método abstracto único (SAM).

Digamos que tenemos que proporcionar un comparador personalizado para el método Collections.sort :

Collections.sort(numbers, new Comparator() { @Override public int compare(Integer n1, Integer n2) { return n1.compareTo(n2); } });

Como podemos ver, esta es una técnica tediosa y detallada, ciertamente no es algo que aliente a los desarrolladores a adoptar la programación funcional. Afortunadamente, Java 8 trajo muchas características nuevas para facilitar el proceso, como expresiones lambda, referencias de métodos e interfaces funcionales predefinidas .

Veamos cómo una expresión lambda puede ayudarnos con la misma tarea:

Collections.sort(numbers, (n1, n2) -> n1.compareTo(n2));

Definitivamente, esto es más conciso y comprensible. Sin embargo, tenga en cuenta que, si bien esto puede darnos la impresión de usar funciones como ciudadanos de primera clase en Java, ese no es el caso.

Detrás del azúcar sintáctico de las expresiones lambda, Java todavía las envuelve en interfaces funcionales. Por lo tanto, Java trata una expresión lambda como un Objeto , que es, de hecho, el verdadero ciudadano de primera clase en Java.

3.2. Funciones puras

La definición de función pura enfatiza que una función pura debe devolver un valor basado solo en los argumentos y no debe tener efectos secundarios . Ahora, esto puede sonar bastante contrario a todas las mejores prácticas en Java.

Java, being an object-oriented language, recommends encapsulation as a core programming practice. It encourages hiding an object's internal state and exposing only necessary methods to access and modify it. Hence, these methods aren't strictly pure functions.

Of course, encapsulation and other object-oriented principles are only recommendations and not binding in Java. In fact, developers have recently started to realize the value of defining immutable states and methods without side-effects.

Let's say we want to find the sum of all the numbers we've just sorted:

Integer sum(List numbers) { return numbers.stream().collect(Collectors.summingInt(Integer::intValue)); }

Now, this method depends only on the arguments it receives, hence, it's deterministic. Moreover, it doesn't produce any side effects.

Side effects can be anything apart from the intended behavior of the method. For instance, side-effects can be as simple as updating a local or global state or saving to a database before returning a value. Purists also treat logging as a side effect, but we all have our own boundaries to set!

We may, however, reason about how we deal with legitimate side effects. For instance, we may need to save the result in a database for genuine reasons. Well, there are techniques in functional programming to handle side effects while retaining pure functions.

We'll discuss some of them in later sections.

3.3. Immutability

Immutability is one of the core principles of functional programming, and it refers to the property that an entity can't be modified after being instantiated. Now in a functional programming language, this is supported by design at the language level. But, in Java, we have to make our own decision to create immutable data structures.

Please note that Java itself provides several built-in immutable types, for instance, String. This is primarily for security reasons, as we heavily use String in class loading and as keys in hash-based data structures. There are several other built-in immutable types like primitive wrappers and math types.

But what about the data structures we create in Java? Of course, they are not immutable by default, and we have to make a few changes to achieve immutability. The use of the final keyword is one of them, but it doesn't stop there:

public class ImmutableData { private final String someData; private final AnotherImmutableData anotherImmutableData; public ImmutableData(final String someData, final AnotherImmutableData anotherImmutableData) { this.someData = someData; this.anotherImmutableData = anotherImmutableData; } public String getSomeData() { return someData; } public AnotherImmutableData getAnotherImmutableData() { return anotherImmutableData; } } public class AnotherImmutableData { private final Integer someOtherData; public AnotherImmutableData(final Integer someData) { this.someOtherData = someData; } public Integer getSomeOtherData() { return someOtherData; } }

Note that we have to observe a few rules diligently:

  • All fields of an immutable data structure must be immutable
  • This must apply to all the nested types and collections (including what they contain) as well
  • There should be one or more constructors for initialization as needed
  • There should only be accessor methods, possibly with no side-effects

It's not easy to get it completely right every time, especially when the data structures start to get complex. However, several external libraries can make working with immutable data in Java easier. For instance, Immutables and Project Lombok provide ready-to-use frameworks for defining immutable data structures in Java.

3.4. Referential Transparency

Referential transparency is perhaps one of the more difficult principles of functional programming to understand. The concept is pretty simple, though. We call an expression referentially transparent if replacing it with its corresponding value has no impact on the program's behavior.

This enables some powerful techniques in functional programming like higher-order functions and lazy evaluation. To understand this better, let's take an example:

public class SimpleData { private Logger logger = Logger.getGlobal(); private String data; public String getData() { logger.log(Level.INFO, "Get data called for SimpleData"); return data; } public SimpleData setData(String data) { logger.log(Level.INFO, "Set data called for SimpleData"); this.data = data; return this; } }

This is a typical POJO class in Java, but we're interested in finding if this provides referential transparency. Let's observe the following statements:

String data = new SimpleData().setData("Baeldung").getData(); logger.log(Level.INFO, new SimpleData().setData("Baeldung").getData()); logger.log(Level.INFO, data); logger.log(Level.INFO, "Baeldung");

The three calls to logger are semantically equivalent but not referentially transparent. The first call is not referentially transparent as it produces a side-effect. If we replace this call with its value as in the third call, we'll miss the logs.

The second call is also not referentially transparent as SimpleData is mutable. A call to data.setData anywhere in the program would make it difficult for it to be replaced with its value.

So basically, for referential transparency, we need our functions to be pure and immutable. These are the two preconditions we've already discussed earlier. As an interesting outcome of referential transparency, we produce context-free code. In other words, we can execute them in any order and context, which leads to different optimization possibilities.

4. Functional Programming Techniques

The functional programming principles that we discussed earlier enable us to use several techniques to benefit from functional programming. In this section, we'll cover some of these popular techniques and understand how we can implement them in Java.

4.1. Function Composition

Function composition refers to composing complex functions by combining simpler functions. This is primarily achieved in Java using functional interfaces, which are, in fact, target types for lambda expressions and method references.

Typically, any interface with a single abstract method can serve as a functional interface. Hence, we can define a functional interface quite easily. However, Java 8 provides us many functional interfaces by default for different use cases under the package java.util.function.

Many of these functional interfaces provide support for function composition in terms of default and static methods. Let's pick the Function interface to understand this better. Function is a simple and generic functional interface that accepts one argument and produces a result.

It also provides two default methods, compose and andThen, which will help us in function composition:

Function log = (value) -> Math.log(value); Function sqrt = (value) -> Math.sqrt(value); Function logThenSqrt = sqrt.compose(log); logger.log(Level.INFO, String.valueOf(logThenSqrt.apply(3.14))); // Output: 1.06 Function sqrtThenLog = sqrt.andThen(log); logger.log(Level.INFO, String.valueOf(sqrtThenLog.apply(3.14))); // Output: 0.57

Both these methods allow us to compose multiple functions into a single function but offer different semantics. While compose applies the function passed in the argument first and then the function on which it's invoked, andThen does the same in reverse.

Several other functional interfaces have interesting methods to use in function composition, such as the default methods and, or, and negate in the Predicate interface. While these functional interfaces accept a single argument, there are two-arity specializations, like BiFunction and BiPredicate.

4.2. Monads

Many of the functional programming concepts derive from Category Theory, which is a general theory of functions in mathematics. It presents several concepts of categories like functors and natural transformations. For us, it's only important to know that this is the basis of using monads in functional programming.

Formally, a monad is an abstraction that allows structuring programs generically. So basically, a monad allows us to wrap a value, apply a set of transformations, and get the value back with all transformations applied. Of course, there are three laws that any monad needs to follow – left identity, right identity, and associativity – but we'll not get into the details.

In Java, there are a few monads that we use quite often, like Optional and Stream:

Optional.of(2).flatMap(f -> Optional.of(3).flatMap(s -> Optional.of(f + s)))

Now, why do we call Optional a monad? Here, Optional allows us to wrap a value using the method of and apply a series of transformations. We're applying the transformation of adding another wrapped value using the method flatMap.

If we want, we can show that Optional follows the three laws of monads. However, critics will be quick to point out that an Optional does break the monad laws under some circumstances. But, for most practical situations, it should be good enough for us.

If we understand monads' basics, we'll soon realize that there are many other examples in Java, like Stream and CompletableFuture. They help us achieve different objectives, but they all have a standard composition in which context manipulation or transformation is handled.

Of course, we can define our own monad types in Java to achieve different objectives like log monad, report monad, or audit monad. Remember how we discussed handling side-effects in functional programming? Well, as it appears, the monad is one of the functional programming techniques to achieve that.

4.3. Currying

Currying is a mathematical technique of converting a function that takes multiple arguments into a sequence of functions that take a single argument. But, why do we need them in functional programming? It gives us a powerful composition technique where we do not need to call a function with all its arguments.

Moreover, a curried function does not realize its effect until it receives all the arguments.

In pure functional programming languages like Haskell, currying is well supported. In fact, all functions are curried by default. However, in Java, it's not that straightforward:

Function
    
      weight = mass -> gravity -> mass * gravity; Function weightOnEarth = weight.apply(9.81); logger.log(Level.INFO, "My weight on Earth: " + weightOnEarth.apply(60.0)); Function weightOnMars = weight.apply(3.75); logger.log(Level.INFO, "My weight on Mars: " + weightOnMars.apply(60.0));
    

Here, we've defined a function to calculate our weight on a planet. While our mass remains the same, gravity varies by the planet we're on. We can partially apply the function by passing just the gravity to define a function for a specific planet. Moreover, we can pass this partially applied function around as an argument or return value for arbitrary composition.

Currying depends upon the language to provide two fundamental features: lambda expressions and closures. Lambda expressions are anonymous functions that help us to treat code as data. We've seen earlier how to implement them using functional interfaces.

Now, a lambda expression may close upon its lexical scope, which we define as its closure. Let's see an example:

private static Function weightOnEarth() { final double gravity = 9.81; return mass -> mass * gravity; }

Please note how the lambda expression, which we return in the method above, depends on the enclosing variable, which we call closure. Unlike other functional programming languages, Java has a limitation that the enclosing scope has to be final or effectively final.

As an interesting outcome, currying also allows us to create a functional interface in Java of arbitrary arity.

4.4. Recursion

Recursion is another powerful technique in functional programming that allows us to break down a problem into smaller pieces. The main benefit of recursion is that it helps us eliminate the side effects, which is typical of any imperative style looping.

Let's see how we calculate the factorial of a number using recursion:

Integer factorial(Integer number) { return (number == 1) ? 1 : number * factorial(number - 1); }

Here, we call the same function recursively until we reach the base case and then start to calculate our result. Notice that we're making the recursive call before calculating the result at each step or in words at the head of the calculation. Hence, this style of recursion is also known as head recursion.

A drawback of this type of recursion is that every step has to hold the state of all previous steps until we reach the base case. This is not really a problem for small numbers, but holding the state for large numbers can be inefficient.

A solution is a slightly different implementation of the recursion known as tail recursion. Here, we ensure that the recursive call is the last call a function makes. Let's see how we can rewrite the above function to use tail recursion:

Integer factorial(Integer number, Integer result) { return (number == 1) ? result : factorial(number - 1, result * number); }

Notice the use of an accumulator in the function, eliminating the need to hold the state at every step of recursion. The real benefit of this style is to leverage compiler optimizations where the compiler can decide to let go of the current function's stack frame, a technique known as tail-call elimination.

While many languages like Scala supports tail-call elimination, Java still does not have support for this. This is part of the backlog for Java and will perhaps come in some shape as part of larger changes proposed under Project Loom.

5. Why Functional Programming Matters?

After going through the tutorial so far, we must wonder why we even want to take this much effort. For someone coming from a Java background, the shift that functional programming demands are not trivial. So, there should be some really promising advantages for adopting functional programming in Java.

The biggest advantage of adopting functional programming in any language, including Java, is pure functions and immutable states. If we think in retrospect, most of the programming challenges are rooted in the side-effects and mutable state one way or the other. Simply getting rid of them makes our program easier to read, reason about, test, and maintain.

Declarative programming, as such, leads to very concise and readable programs. Functional programming, being a subset of declarative programming, offers several constructs like higher-order functions, function composition, and function chaining. Think of the benefits that Stream API has brought into Java 8 for handling data manipulations.

But don't get tempted to switch over unless completely ready. Please note that functional programming is not a simple design pattern that we can immediately use and benefit from. Functional programming is more of a change in how we reason about problems and their solutions and how to structure the algorithm.

So, before we start using functional programming, we must train ourselves to think about our programs in terms of functions.

6. Is Java a Suitable Fit?

While it's difficult to deny functional programming benefits, we cannot help but ask ourselves if Java is a suitable choice for it. Historically, Java evolved as a general-purpose programming language more suitable for object-oriented programming. Even thinking of using functional programming before Java 8 was tedious! But things have definitely changed after Java 8.

The very fact that there are no true function types in Java goes against functional programming's basic principles. The functional interfaces in the disguise of lambda expressions make up for it largely, at least syntactically. Then, the fact that types in Java are inherently mutable and we have to write so much boilerplate to create immutable types does not help.

We expect other things from a functional programming language that are missing or difficult in Java. For instance, the default evaluation strategy for arguments in Java is eager. But, lazy evaluation is a more efficient and recommended way in functional programming.

We can still achieve lazy evaluation in Java using operator short-circuiting and functional interfaces, but it's more involved.

The list is certainly not complete and can include generics support with type-erasure, missing support for tail-call optimization, and other things. However, we get a broad idea. Java is definitely not suitable for starting a program from scratch in functional programming.

But what if we already have an existing program written in Java, probably in object-oriented programming? Nothing stops us from getting some of the benefits of functional programming, especially with Java 8.

This is where most of the benefits of functional programming lie for a Java developer. A combination of object-oriented programming with the benefits of functional programming can go a long way.

7. Conclusion

In this tutorial, we went through the basics of functional programming. We covered the fundamental principles and how we can adopt them in Java. Further, we discussed some popular techniques in functional programming with examples in Java.

Finally, we covered some of the benefits of adopting functional programming and answered if Java is suitable for the same.

El código fuente del artículo está disponible en GitHub.