Post

Monads in Java

Pre-read blogs:

  1. Functional Programming in Java - What and Why?
  2. Functional Interface examples (Functional programming)

Monads

Let me take a very simple concept of doing 3 operations one after the other with the output of one fed to another.

1
2
3
Integer firstOutput = firstOperation(firstInput)
Integer secondOutput = secondOperation(firstOutput)
Integer thirdOutput = thirdOperation(secondOutput)

In the above set of operations, we might encounter a Null in any of the operations.

In the verbose way, we ideally would do the following to avoid NullPointerException:

1
2
3
4
5
6
7
Integer firstOutput = firstOperation(firstInput)
if (firstOutput != null) {
    Integer secondOutput = secondOperation(firstOutput)
    if (secondOutput != null) {
        Integer thirdOutput = thirdOperation(secondOutput)
    }
}

The above code is not that intuitive at all.

Let’s look at the monad way of doing things to make it clear.

Note: Optional.of() wraps a value and returns Optional.none() if the value is null.

1
2
3
Optional<Integer> firstOutput = Optional.of(firstOperation(firstInput))
Optional<Integer> secondOutput = firstOutput.map(output -> secondOperation(output)).orElse(Optional.none())
Optional<Integer> thirdOutput = firstOutput.map(output -> thirdOperation(output)).orElse(Optional.none())

Simplified as:

1
2
3
4
Optional<Integer> finalResult = Optional.of(firstOperation(firstInput))
                                        .map(firstOutput -> Optional.of(secondOperation(firstOutput)))
                                        .map(secondOutput -> Optional.of(thirdOperation(secondOutput))
                                        .orElse(Optional.none())

Monads help in simplifying code and avoids the infamous NullPointerException in the production code.


This post is licensed under CC BY 4.0 by the author.