1. Overview

In this tutorial, we’re going to discuss Monads and their definition using Java. The idea is to understand the concept, what problems it addresses, and how the Java language implements it.

By the end of it, we hope one can understand the Monads and how to make the most of it.

2. The Concept

The Monad is a design pattern popular in the functional programming world. However, it actually originated from a mathematical field called Category Theory. This article will focus on Monad’s definition of the software engineering field. Although both definitions have many similarities, the software one and the field’s jargon are more relevant to our context.

In short, a general concept is an object that can map itself to different results based on transformations.

3. The Design Pattern

Monads are containers or structures that encapsulate values and computations. They must have two basic operations:

  • Unit: monads represent a type that wraps a given value, and this operation is responsible for wrapping the value. For example, in Java, this operation can accept values from different types just by leveraging generics
  • Bind: This operation allows transformation to be executed using the held value and returns a new monad value (a value wrap in the monad type)

Nonetheless, there are some properties that a monad has to obey:

  • Left identity: when applying to a monad, it should yield the same outcome as applying the transformation to the held value
  • Right identity: when sending a monad transformation (convert the value to a monad), the yield outcome must be the same as wrapping the value in a new monad
  • Associativity: when chaining transformations, it should not matter how transformations are nested

One of the challenges of functional programming is to allow pipelining of such operations without losing readability. This is one of the reasons for adopting the concept of monads. The Monad is fundamental to the functional paradigm and helps implement declarative programming.

4. Java Interpretation

Java 8 implemented the Monad design pattern through classes like OptionalHowever, let’s first look at a code before the addition of the Optional class:

public class MonadSample1 {
    //... 
    private double multiplyBy2(double n) {
        return n * 2;
    }

    private double divideBy2(double n) {
        return n / 2;
    }

    private double add3(double n) {
        return n + 3;
    }

    private double subtract1(double n) {
        return n - 1;
    }

    public double apply(double n) {
        return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(n)))));
    }
    //... 
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenNotUsingMonad_shouldBeOk() {
        MonadSample1 test = new MonadSample1();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //... 
}

As we can observe, the apply method looks quite hard to read, but what would be the alternative to it? Maybe the following:

public class MonadSample2 {
    //... 
    public double apply(double n) { 
        double n1 = multiplyBy2(n); 
        double n2 = multiplyBy2(n1); 
        double n3 = divideBy2(n2); 
        double n4 = add3(n3); 
        return subtract1(n4); 
    } 
    //...
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenNotUsingMonadButUsingTempVars_shouldBeOk() {
        MonadSample2 test = new MonadSample2();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //...
}

This seems better, but it still looks too verbose. So let’s see what it would be like using Optional:

public class MonadSample3 {
    //...
    public double apply(double n) {
        return Optional.of(n)
          .flatMap(value -> Optional.of(multiplyBy2(value)))
          .flatMap(value -> Optional.of(multiplyBy2(value)))
          .flatMap(value -> Optional.of(divideBy2(value)))
          .flatMap(value -> Optional.of(add3(value)))
          .flatMap(value -> Optional.of(subtract1(value)))
          .get();
    }
    //...
public class MonadSampleUnitTest {
    //...
    @Test
    public void whenUsingMonad_shouldBeOk() {
        MonadSample3 test = new MonadSample3();
        Assert.assertEquals(6.0, test.apply(2), 0.000);
    }
    //...
}

The code above seems cleaner. On the other hand, this design allows developers to apply as many subsequent transformations as needed without sacrificing readability and reducing the verboseness of the temporary variables declarations.

There is more; imagine if any of those functions could produce null values. In such a case, we would have to add validation before each transformation, making the code more verbose. That is actually the primary purpose of the Optional class. The idea was to avoid working with null and provide an easy-to-use way to apply transformations to objects so that when they aren’t null, a series of declarations will be executed in a null-safe manner. It’s also possible to check if the value wrapped by the Optional is empty or not (has a value null).

4.1. Optional Caveats

As described at the beginning, Monads need to have some operations and properties, so let’s look at those properties in the Java implementation. First, why not check the operations that a Monad must have:

  • For Unit operations, Java offers different flavors like Optional.of() and Optional.nullable(). As we may imagine, one accepts null values, and the other does not
  • As for the Bind function, Java offers the Optional.flatMap() operation, introduced in the code examples

A feature that is not in the definition of a Monad is the map operation. It is a transformation and chain operation similar to flatMap. The difference between the two is that the map operation receives a transformation that returns a raw value to be wrapped internally by the API. While the flatMap already returns a wrapped value that the API returns to form the pipeline.

Now, let’s examine the properties of the Monad:

public class MonadSample4 {
    //... 
    public boolean leftIdentity() {
         Function<Integer, Optional> mapping = value -> Optional.of(value + 1);
         return Optional.of(3).flatMap(mapping).equals(mapping.apply(3));
     }

     public boolean rightIdentity() {
         return Optional.of(3).flatMap(Optional::of).equals(Optional.of(3));
     }

     public boolean associativity() {
         Function<Integer, Optional> mapping = value -> Optional.of(value + 1);
         Optional leftSide = Optional.of(3).flatMap(mapping).flatMap(Optional::of);
         Optional rightSide = Optional.of(3).flatMap(v -> mapping.apply(v).flatMap(Optional::of));
         return leftSide.equals(rightSide);
     }
     //... 
public class MonadSampleUnitTest {
    //...  
    @Test
    public void whenTestingMonadProperties_shouldBeOk() {
        MonadSample4 test = new MonadSample4();
        Assert.assertEquals(true, test.leftIdentity());
        Assert.assertEquals(true, test.rightIdentity());
        Assert.assertEquals(true, test.associativity());
    }
    //...
}

At first glance, all properties seem to comply with the requirements, and Java has a proper Monad implementation, but this is not actually the case. Let’s try one more test:

class MonadSample5 {
    //...
    public boolean fail() {
        Function<Integer, Optional> mapping = value -> Optional.of(value == null ? -1 : value + 1);
        return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null));
    }
    //...
class MonadSampleUnitTest {
    @Test
    public void whenBreakingMonadProperties_shouldBeFalse() {
        MonadSample5 test = new MonadSample5();
        Assert.assertEquals(false, test.fail());
    }
    //...
}

As observed, the left identity property from Monad was broken. Actually, this seems to be a conscious decision, as per this discussion. One member of the JDK team says Optional has a narrower scope than other languages, and they don’t intend it to be more than that. There are other scenarios where such properties may not hold.

Actually, other APIs, like streams, have a similar design but don’t intend to implement the Monad specification fully.

5. Conclusion

In this article, we looked at the concept of Monad, how they were introduced in Java, and the nuances of such implementation.

One can argue that what Java has is not actually a Monad implementation and that when designing for null safety, they broke the principles. However, many of the benefits of such a pattern are still there.

As usual, all code samples used in this article are available over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.