Towards better functional programming in Java with Vavr
Tags: java, vavr, functional
Published: 2020-07-14 11:34:16

<p>The functional paradigm in programming is over 62 years old, first presented in the Lisp language in 1958<strong><a href="#refs"><sup>1</sup></a></strong>. In the context of the Java language, it began to be widely spoken relatively recently from the perspective of these years because from version 1.8 or 6 years ago. So what is functional programming, can we program functionally in Java, can we reconcile this paradigm with OOP and how can Vavr library help us in all this?</p>
<h2><strong>Starting from the beginning</strong></h2>
<p>Before we get into the library itself, let’s briefly recall what functional programming is and what its assumptions are.</p>
<p>The most important assumption of functional programming (FP) is the lack of the so-called side effects where there are many approaches, solutions or language features that bring us closer to this goal, and they include:</p>
<ul>
<li>Immutability</li>
<li>Lazy initialization</li>
<li>Declarative programming language</li>
<li>First-class functions</li>
<li>Higher-order functions</li>
</ul>
<p>Explanation what each of these mean is beyond the scope of this article, but for those interested in learning more, I’ve listed some good reading material <strong><a href="https://www.amazon.com/Functional-Programming-Java-functional-techniques/dp/1617292737" target="_blank" rel="noopener noreferrer">in the references</a></strong>.</p>
<p>As for the FP pillar, lack of side effects, it is a situation where a given function call does not cause a side effect in the system and retains the so-called referential transparency. This means, no less, no more that we should be able to replace the call of our function for given input parameters with its value. In other words, the function should be deterministic for the arguments given to it and should always return the same result without causing any change in the state of the system except the function scope.</p>
<p>However this does not mean that we must completely abandon mutation operations, after all, it would be impossible to write a system based on business requirements without a database, cache or even http requests. The main thing is that actions that change some state should be extracted as far as possible, should be explicitly marked and ideally be performed at one point in the codebase, ideally in the main class or some dedicated module.</p>
<h2><strong>Functional Programming in Java?</strong></h2>
<p>A common complaint against Java is its simple syntax and the lack of so-called syntactic sugar. The amount of code needed to write a given functionality, compared to the languages &#8203;&#8203;that put the functional paradigm in the first place in their foundations<sup><a href="#refs"><strong>2</strong></a></sup>, is definitely larger. It is also true that these languages &#8203;&#8203;have a higher entry threshold than Java, it is definitely easier to find a Java programmer than Clojure or Scala, which often has an impact on the main language in which the project will be written. In addition, Java is a huge percentage of the current market, many projects have been written or are in the process of writing in Java, and it would often be impossible to rewrite it to a new language with better language constructions to enjoy the benefits of using the FP paradigm. Simply put – sometimes we have no way of changing the language, and yet we would like to try working with a new paradigm. That is why, starting from Java version 8 and thanks to constructions implemented in the Vavr library<a href="#refs"><sup><strong>3</strong></sup></a>, this desire becomes feasible.</p>
<h2><strong>Vavr</strong></h2>
<p><strong><a href="https://github.com/vavr-io/vavr" target="_blank" rel="noopener noreferrer">Vavr</a></strong>, <strong><a href="http://blog.vavr.io/javaslang-changes-name-to-vavr/" target="_blank" rel="noopener noreferrer">formerly Java Slang</a></strong>, is a library made available under Apache 2.0 license, which provides us with tools that facilitate functional programming using Java. It is worth noting that Vavr does not contain any dependencies on external libraries, and is based solely on the API offered by Java.<br>
Thanks to lambda expressions<a href="#refs"><strong><sup>4</sup></strong></a>, functional interfaces<a href="#refs"><strong><sup>5</sup></strong></a>, var keyword<a href="#refs"><strong><sup>6</sup></strong></a> along with the use of components from the Vavr library, functional programming in Java becomes possible. The library itself consists of logically separated modules such as: gwt, match, test, jackson, gson, render, which have been implemented around the main core module and we will look at the selected elements of this module.</p>
<h2><strong>Scary Monads and how to embrace them</strong></h2>
<p>To better understand the concepts implemented in the Vavr library we will need another definition, the definition of Monad. This sinister-sounding name, which has its roots in Category Theory<a href="#refs"><strong><sup>7</sup></strong></a>, for the purposes of this article and in simplification, it can be broken down to simple to understand description – a Monad is a container for data, which allows us to operate declaratively on the data, using operations that are common to other Monads. There is a high probability that if you have not come across this term before, you have unwittingly used the Monads themselves, e.g. using the Monad introduced in JDK 1.8 – Optional<a href="#refs"><strong><sup>8</sup></strong></a> class. In the context of the description presented earlier, the Optional class is a container for data or lack thereof, and provides a set of API enabling declarative operations on this data, including among others operations:</p>
<p style="padding-left: 40px;"><strong>map</strong> – enabling a function to be performed on a given data<br>
<strong>flatmap</strong> – enabling a function to be performed on data that is already a monad, in other words, flattening data<br>
<strong>filter</strong> – filtering-out data that is not of interest for us<br>
<strong>stream<a href="#refs"><sup>9</sup></a> </strong>– converting from Optional Monad to Stream<a href="#refs"><strong><sup>10</sup></strong></a> Monad</p>
<p>It is worth noting that, as already mentioned, the counterparts of these operations can also be found in other Monads, so when we have to work with the Monad supplied from a given library, we should be able to call functions on data, flatten data, filter data or convert to another Monad. These are, of course, only some of the operations available on Monads, and the available API strongly depends on the library provider or own creative invention of the author.</p>
<p>Getting to the point, the Vavr library provides us with 5 basic monads, and these are:</p>
<h3><a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/control/Either.html" target="_blank" rel="noopener noreferrer"><strong>Either</strong></a></h3>
<p>Either represents the result in which we can return one of two values &#8203;&#8203;- left or right. Used when the call to our method can have two waveforms, for example in a situation where the result of a given operation may fail – assigning it the value left, and in the case of success the value right.</p>
<h3><a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/control/Option.html" target="_blank" rel="noopener noreferrer"><strong>Option</strong></a></h3>
<p>Monad used in a situation where we explicitly want to express the intention in which calling our method may return the result or lack of result. The main advantage as opposed to using the @Nullable annotation<a href="#refs"><strong><sup>11</sup></strong></a> or Javadoc describing a possible null result is that we described the situation using an object that is part of the method signature, and thus handling the situation where the result would be not present is required and checked by the compiler. The most important difference between Option and Optional is that the mapping function that returns null will throw an exception. In addition, this Monad provides a richer set of APIs, including the fold method, which allows us to perform a value mapping operation in the absence or existence of it. Examples of using the Option:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6yfbfwcmvlr5kpr36a1z.png)

<p>
In the presented implementation, the Book module provides the operation of finding information about a book based on ISBN using the findBookDetails method, which uses the Option Monad in its signature. The API user is obliged to handle the situation in which the data about the book is not available through the type contained in the signature, otherwise he will receive a compilation error.</p>
<p>An example implementation of operations based on the Option API along with Either API looks following:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vaw8l64ew762l2yvd6lh.png)

<p><strong>Where:</strong><br>
Lines 11-12 handle potential null values &#8203;&#8203;from the ISBN object passed from the user of our API, to further on line 13 perform http request which will return the result wrapped in Either Monad. The whole is handled in line 14, where in the absence of values &#8203;&#8203;from previous calls we return an empty result, and in the case of having data and invoking the request, we handle the result by mapping Either Monad to the Option Monad and calling the toDto method from the BookData object.</p>
<h3><a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/control/Try.html" target="_blank" rel="noopener noreferrer"><strong>Try</strong></a></h3>
<p>Monad Try is similar to Option Monad, except that in contrast to missing values &#8203;&#8203;it stores an exception that may have been thrown when calling the function. It is worth considering using this monad instead of using checked-exception or instead of throwing runtime exceptions and catching them with the help of framework mechanisms. Instead, we can treat our exceptions as standard Objects and handle errors on a regular basis or postpone their handling to a selected place. Examples of using Try Monad with the Either Monad:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/86bd6cvhkdjiv4ickf4z.png)

<p><strong>Where:</strong><br>
Line 16 starts using Try by wrapping the getBookData method call from the ThirdPartyBookStoreLibrary class with the checked-exception signature.<br>
Thanks to the Vavr library, we can move on and give up the imperative style – the definition of the try catch block, to the declarative style, while handling an exception.<br>
On line 17, in the case of an exception thrown by the getBookData method, we log the situation, then on line 18 we convert to Either Monad by calling mapLeft in line 19, in which we translate the exception from the library into a comprehensible one inside our system.</p>
<p>In addition, on line 19 the property of functional interfaces was used – use of a qualifier, so we can skip the name of the called method.</p>
<h3><a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/Lazy.html" target="_blank" rel="noopener noreferrer"><strong>Lazy</strong></a></h3>
<p>Monad Lazy represents the value obtained not at the stage of initialization, but at the moment of referring to the value itself, in this context we refer to this as lazy initialization. Its operation can be compared to the known from Java 8 interface Supplier&lt;T&gt;, which returns a given value, with the difference that Lazy Monad has implemented the Memoization functionality and meets the aforementioned Referential transparency and which means that for the same set of arguments Monad calculates the result only once and stores it, returning calculated value for further invocations. An example of using Lazy Monad:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u6m092fkzvb897fy7jvb.png)

<p><strong>Where:</strong><br>
On line 5 we passed a dependency returning a list of available books, the operation of fetching available books was defined outside the Library class and is expensive because it requires invoking multiple HTTP requests. By using Lazy Monad, we postpone the invocation of expensive calls until the first invocation of the getAvailableBooks method, and this result is saved thanks to the previously mentioned memoization functionality.</p>
<h3><a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/concurrent/Future.html" target="_blank" rel="noopener noreferrer"><strong>Future</strong></a></h3>
<p>Last of the Monads provided in the Vavr library – Future Monad represents value, the result of which will be made available somewhere in time. Operations on this monad are non-blocking. In its behaviour, it resembles the Future / CompletableFuture classes known from JDK. An example of using Future Monad:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/htrwey0g7l912mj2h74w.png)

<p><strong>Where:</strong><br>
Line 13 transforms the passed Set collection to Stream Monad<br>
Line 14 calls the findBookDetails method that wraps the call of the BookService method in the Future.of method call with the use of the injected Executor dependency<br>
Line 15 collects the result, transforms it to a list and then the result is passed to the sequence method from the Future class<br>
Last Lines 16 and 17 are responsible for collecting the result and creating a new AvailableBooksResult object and returning it in the Future monad. In this way we have achieved functionality in which we can, without blocking, download information about available books.</p>
<h2><strong>Briefly about collections and pattern matching</strong></h2>
<p>When it comes to the modification of state mentioned many times, you might have the irresistible impression that we have a problem in the Java world. This problem is the lack of the immutable collections. They all modify the internal state, and when it comes to <em>unmodifiable view</em> methods from the Collections class, they only make our collection become read only, which in many cases may not be enough. In the case that we would like our collection to be fully immutable, Vavr library provides us with a solution in the form of newly defined “Functional Data Structures”, which includes Seq, Set and Map interfaces, all implementing a common interface – Iterable. The review of implementations available in the Vavr library goes far beyond this article, after all, we have available at the time of writing this article 15 implementations, but I strongly encourage you to read <a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/collection/package-summary.html" target="_blank" rel="noopener noreferrer"><strong>their documentation</strong></a> about it.</p>
<p>Another element provided in the Vavr library, and often a part of many functional languages<a href="#refs"><strong><sup>12</sup></strong></a> is Pattern Matching. Simply put, Pattern Matching allows you to declaratively define control based on a given condition so-called “Match predicate”. An example of using Pattern Matching from the Vavr library looks like this:</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1sizu7jwivpk9exevf79.png)

<p><strong>Where:</strong><br>
Line 2 Starts Pattern Matching consisting of predicates from lines 2 to 5 and when:<br>
Instance of Number object is BigDecimal type, it calls and returns the result of add method from BigDecimal<br>
Instance of Number object is of the BigInteger type, it calls and returns the result of the add method from the BigInteger class.<br>
Instance of the Number object is of the Integer type, sums the value and returns the result.<br>
Instance of the Number object is of the Float type, sums the value and returns the result.</p>
<p>In addition to the <a href="https://www.javadoc.io/static/io.vavr/vavr/0.10.1/io/vavr/Predicates.html" target="_blank" rel="noopener noreferrer"><strong>predicates</strong> </a>provided by the Vavr library, it is possible to define your own predicates and use them with the mechanism presented above by utilizing the <a href="https://github.com/vavr-io/vavr-match" target="_blank" rel="noopener noreferrer"><strong>vavr-match</strong></a> module.</p>
<p>It is worth adding that Type Pattern Matching is slowly being implemented in Java. Switch expressions have been added the JDK 14<a href="#refs"><strong><sup>13</sup></strong></a> which makes it possible to use the switch statement also as expressions moreover in the JDK 14 version, authors introduced Pattern Matching for the <strong>instance of</strong> instruction in the preview version, which has been further transferred to the JDK 15 version in the second preview version<a href="#refs"><strong><sup>14</sup></strong></a>.</p>
<h2><strong>Summary</strong></h2>
<p>Despite being 62 years old, functional programming is doing very well and has not been forgotten but is a paradigm that is used on a daily basis. Languages &#8203;&#8203;are more and more boldly adapting the functional paradigm, and programmers are noticing the benefits behind its use. The world of Java and OOP does not necessarily exclude the use of FP in existing or new projects, Java syntax has been improved over the years, which is why together with the use of libraries supporting functional programming and concepts implemented there, nowadays we can be tempted to introduce a new paradigm to our codebase. This will allow us to better abstract side effects, help us create code resistant to multithreading problems, code that is more predictable and thus better maintained over time. In the article I have included basic concepts regarding FP and briefly presented the use of selected elements of the Vavr library, which are only a brief introduction to the whole range of solutions and approaches that can be implemented. If you first came across the approaches described in the article I strongly encourage you to explore the subject further because this knowledge will definitely pay off in the future and can give a different point of view on certain problems.</p>
<p>&nbsp;</p>
<hr id="refs">
<p><sup>1&nbsp;</sup> <small>For those interested, I present a <a href="https://www.cs.kent.ac.uk/people/staff/dat/tfp12/tfp12.pdf">paper </a>describing the history of functional languages.</small><br>
<sup>2&nbsp;</sup> <small> In the world of JVM it will be, for example, <a href="https://www.scala-lang.org" target="_blank" rel="noopener noreferrer">Scala</a> or <a href="https://clojure.org" target="_blank" rel="noopener noreferrer">Clojure</a>.</small><br>
<sup>3&nbsp;</sup> <small>For Java, there are other libraries that facilitate functional programming, such as <a href="https://github.com/aol/cyclops" target="_blank" rel="noopener noreferrer">Cyclops</a> or <a href="https://github.com/functionaljava/functionaljava" target="_blank" rel="noopener noreferrer">Functional Java</a>, however the article focuses solely on the Vavr library.</small><br>
<sup>4&nbsp;</sup> <small>Added in JDK 1.8, <a href="https://openjdk.java.net/jeps/126" target="_blank" rel="noopener noreferrer">JEP 126</a>.</small><br>
<sup>5&nbsp;</sup> <small>Added in <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html" target="_blank" rel="noopener noreferrer">JDK 1.8</a>.</small><br>
<sup>6&nbsp;</sup> <small>Added in JDK 11, <a href="https://openjdk.java.net/jeps/286" target="_blank" rel="noopener noreferrer">JEP 286</a>. The keyword var is not required for a functional approach, but it helps when reading heavily nested Monads for example.</small><br>
<sup>7&nbsp;</sup> <small>For those interested, I’m leaving a <a href="https://github.com/hmemcpy/milewski-ctfp-pdf" target="_blank" rel="noopener noreferrer">link</a> to a GitHub page with a source of the book “Category Theory for Programmers” written by Bartosz Milewski. The book in pdf version published under the GNU GPL v.3 license.</small><br>
<sup>8&nbsp;</sup> <small>In the context of Monad laws, the Optional class does not meet all the criteria needed to be considered a true Monad, while for the purposes of this article I have adopted a simplified comparison.</small><br>
<sup>9&nbsp;</sup> <small><a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html#stream()" target="_blank" rel="noopener noreferrer">The method</a> added in JDK 9.</small><br>
<sup>10&nbsp;</sup> <small>Again, for the purposes of the article, I assumed that <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" target="_blank" rel="noopener noreferrer">Stream</a> class meets all Monad laws, in practice this class is not a full-fledged Monad, more can be read <a href="https://patternsinfp.wordpress.com/2010/12/31/stream-monad/" target="_blank" rel="noopener noreferrer">in this article</a>.</small><br>
<sup>11&nbsp;</sup> <small>Although current IDEs are able to catch such errors and there are <a href="https://github.com/spotbugs/spotbugs" target="_blank" rel="noopener noreferrer">plugins</a> that can analyze our annotations and at the build stage allowing to capture such places, while these are external tools and you should take care of their appropriate configuration.</small><br>
<sup>12&nbsp;</sup> <small><a href="https://docs.scala-lang.org/tour/pattern-matching.html" target="_blank" rel="noopener noreferrer">Scala Pattern Matching</a>, <a href="https://www.haskell.org/tutorial/patterns.html" target="_blank" rel="noopener noreferrer">Haskell Pattern Matching</a>.</small><br>
<sup>13&nbsp;</sup> <small><a href="https://openjdk.java.net/jeps/361" target="_blank" rel="noopener noreferrer">JEP 361</a>.</small><br>
<sup>14&nbsp;</sup> <small><a href="https://openjdk.java.net/jeps/305" target="_blank" rel="noopener noreferrer">JEP 305</a> and <a href="https://openjdk.java.net/jeps/375" target="_blank" rel="noopener noreferrer">JEP 375</a>.</small></p>