1. Introduction
Fugue is a Java library by Atlassian; it’s a collection of utilities supporting Functional Programming.
In this write-up, we’ll focus on and explore the most important Fugue’s APIs.
2. Getting Started With Fugue
To start using Fugue in our projects, we need to add the following dependency:
<dependency>
<groupId>io.atlassian.fugue</groupId>
<artifactId>fugue</artifactId>
<version>4.5.1</version>
</dependency>
We can find the most recent version of Fugue over on Maven Central.
3. Option
Let’s start our journey by looking at the Option class which is Fugue’s answer to java.util.Optional.
As we can guess by the name, Option’s a container representing a potentially absent value.
In other words, an Option is either Some value of a certain type or None:
Option<Object> none = Option.none();
assertFalse(none.isDefined());
Option<String> some = Option.some("value");
assertTrue(some.isDefined());
assertEquals("value", some.get());
Option<Integer> maybe = Option.option(someInputValue);
3.1. The map Operation
One of the standard Functional Programming APIs is the map() method which allows applying a provided function to underlying elements.
The method applies the provided function to the Option‘s value if it’s present:
Option<String> some = Option.some("value")
.map(String::toUpperCase);
assertEquals("VALUE", some.get());
3.2. Option and a Null Value
Besides naming differences, Atlassian did make a few design choices for Option that differ from Optional; let’s now look at them.
We cannot directly create a non-empty Option holding a null value:
Option.some(null);
The above throws an exception.
However, we can get one as a result of using the map() operation:
Option<Object> some = Option.some("value")
.map(x -> null);
assertNull(some.get());
This isn’t possible when simply using java.util.Optional.
*3.3. Option Is Iterable*
Option can be treated as a collection that holds maximum one element, so it makes sense for it to implement the Iterable interface.
This highly increases the interoperability when working with collections/streams.
And now, for example, can be concatenated with another collection:
Option<String> some = Option.some("value");
Iterable<String> strings = Iterables
.concat(some, Arrays.asList("a", "b", "c"));
3.4. Converting Option to Stream
Since an Option is an Iterable, it can be converted to a Stream easily too.
After converting, the Stream instance will have exactly one element if the option is present, or zero otherwise:
assertEquals(0, Option.none().toStream().count());
assertEquals(1, Option.some("value").toStream().count());
3.5. java.util.Optional Interoperability
If we need a standard Optional implementation, we can obtain it easily using the toOptional() method:
Optional<Object> optional = Option.none()
.toOptional();
assertTrue(Option.fromOptional(optional)
.isEmpty());
3.6. The Options Utility Class
Finally, Fugue provides some utility methods for working with Options in the aptly named Options class.
It features methods such as filterNone for removing empty Options from a collection, and flatten for turning a collection of Options into a collection of enclosed objects, filtering out empty Options.
Additionally, it features several variants of the lift method that lifts a Function<A,B> into a Function<Option, Option>:
Function<Integer, Integer> f = (Integer x) -> x > 0 ? x + 1 : null;
Function<Option<Integer>, Option<Integer>> lifted = Options.lift(f);
assertEquals(2, (long) lifted.apply(Option.some(1)).get());
assertTrue(lifted.apply(Option.none()).isEmpty());
This is useful when we want to pass a function which is unaware of Option to some method that uses Option.
Note that, just like the map method, lift doesn’t map null to None:
assertEquals(null, lifted.apply(Option.some(0)).get());
4. Either for Computations With Two Possible Outcomes
As we’ve seen, the Option class allows us to deal with the absence of a value in a functional manner.
However, sometimes we need to return more information than “no value”; for example, we might want to return either a legitimate value or an error object.
The Either class covers that use case.
An instance of Either can be a Right or a Left but never both at the same time.
By convention, the right is the result of a successful computation, while the left is the exceptional case.
4.1. Constructing an Either
We can obtain an Either instance by calling one of its two static factory methods.
We call right if we want an Either containing the Right value*:*
Either<Integer, String> right = Either.right("value");
Otherwise, we call left:
Either<Integer, String> left = Either.left(-1);
Here, our computation can either return a String or an Integer.
4.2. Using an Either
When we have an Either instance, we can check whether it’s left or right and act accordingly:
if (either.isRight()) {
...
}
More interestingly, we can chain operations using a functional style:
either
.map(String::toUpperCase)
.getOrNull();
4.3. Projections
The main thing that differentiates Either from other monadic tools like Option, Try, is the fact that often it’s unbiased. Simply put, if we call the map() method, Either doesn’t know if to work with Left or Right side.
This is where projections come in handy.
Left and right projections are specular views of an Either that focus on the left or right value, respectively:
either.left()
.map(x -> decodeSQLErrorCode(x));
In the above code snippet, if Either is Left, decodeSQLErrorCode() will get applied to the underlying element. If Either is Right, it won’t. Same the other way around when using the right projection.
4.4. Utility Methods
As with Options, Fugue provides a class full of utilities for Eithers, as well, and it’s called just like that: Eithers.
It contains methods for filtering, casting and iterating over collections of Eithers.
5. Exception Handling with Try
We conclude our tour of either-this-or-that data types in Fugue with another variation called Try.
Try is similar to Either, but it differs in that it’s dedicated for working with exceptions.
Like Option and unlike Either, Try is parameterized over a single type, because the “other” type is fixed to Exception (while for Option it’s implicitly Void).
So, a Try can be either a Success or a Failure:
assertTrue(Try.failure(new Exception("Fail!")).isFailure());
assertTrue(Try.successful("OK").isSuccess());
5.1. Instantiating a Try
Often, we won’t be creating a Try explicitly as a success or a failure; rather, we’ll create one from a method call.
Checked.of calls a given function and returns a Try encapsulating its return value or any thrown exception:
assertTrue(Checked.of(() -> "ok").isSuccess());
assertTrue(Checked.of(() -> { throw new Exception("ko"); }).isFailure());
Another method, Checked.lift, takes a potentially throwing function and lifts it to a function returning a Try:
Checked.Function<String, Object, Exception> throwException = (String x) -> {
throw new Exception(x);
};
assertTrue(Checked.lift(throwException).apply("ko").isFailure());
5.2. Working With Try
Once we have a Try, the three most common things we might ultimately want to do with it are:
- extracting its value
- chaining some operation to the successful value
- handling the exception with a function
Besides, obviously, discarding the Try or passing it along to other methods, the above three aren’t the only options that we have, but all the other built-in methods are just a convenience over these three.
5.3. Extracting the Successful Value
To extract the value, we use the getOrElse method:
assertEquals(42, failedTry.getOrElse(() -> 42));
It returns the successful value if present, or some computed value otherwise.
There is no getOrThrow or similar, but since getOrElse doesn’t catch any exception, we can easily write it:
someTry.getOrElse(() -> {
throw new NoSuchElementException("Nothing to get");
});
5.4. Chaining Calls After Success
In a functional style, we can apply a function to the success value (if present) without extracting it explicitly first.
This is the typical map method we find in Option, Either and most other containers and collections:
Try<Integer> aTry = Try.successful(42).map(x -> x + 1);
It returns a Try so we can chain further operations.
Of course, we also have the flatMap variety:
Try.successful(42).flatMap(x -> Try.successful(x + 1));
5.5. Recovering From Exceptions
We have analogous mapping operations that work with the exception of a Try (if present), rather than its successful value.
However, those methods differ in that their meaning is to recover from the exception, i.e. to produce a successful Try in the default case.
Thus, we can produce a new value with recover:
Try<Object> recover = Try
.failure(new Exception("boo!"))
.recover((Exception e) -> e.getMessage() + " recovered.");
assertTrue(recover.isSuccess());
assertEquals("boo! recovered.", recover.getOrElse(() -> null));
As we can see, the recovery function takes the exception as its only argument.
If the recovery function itself throws, the result is another failed Try:
Try<Object> failure = Try.failure(new Exception("boo!")).recover(x -> {
throw new RuntimeException(x);
});
assertTrue(failure.isFailure());
The analogous to flatMap is called recoverWith:
Try<Object> recover = Try
.failure(new Exception("boo!"))
.recoverWith((Exception e) -> Try.successful("recovered again!"));
assertTrue(recover.isSuccess());
assertEquals("recovered again!", recover.getOrElse(() -> null));
6. Other Utilities
Let’s now have a quick look at some of the other utilities in Fugue, before we wrap it up.
6.1. Pairs
A Pair is a really simple and versatile data structure, made of two equally important components, which Fugue calls left and right:
Pair<Integer, String> pair = Pair.pair(1, "a");
assertEquals(1, (int) pair.left());
assertEquals("a", pair.right());
Fugue doesn’t provide many built-in methods on Pairs, besides mapping and the applicative functor pattern.
However, Pairs are used throughout the library and they are readily available for user programs.
The next poor person’s implementation of Lisp is just a few keystrokes away!
6.2. Unit
Unit is an enum with a single value which is meant to represent “no value”.
It’s a replacement for the void return type and Void class, that does away with null:
Unit doSomething() {
System.out.println("Hello! Side effect");
return Unit();
}
Quite surprisingly, however, Option doesn’t understand Unit, treating it like some value instead of none.
6.3. Static Utilities
We have a few classes packed full of static utility methods that we won’t have to write and test.
The Functions class offers methods that use and transform functions in various ways: composition, application, currying, partial functions using Option, weak memoization et cetera.
The Suppliers class provides a similar, but more limited, collection of utilities for Suppliers, that is, functions of no arguments.
Iterables and Iterators, finally, contain a host of static methods for manipulating those two widely used standard Java interfaces.
7. Conclusion
In this article, we’ve given an overview of the Fugue library by Atlassian.
We haven’t touched the algebra-heavy classes like Monoid and Semigroups because they don’t fit in a generalist article.
However, you can read about them and more in the Fugue javadocs and source code.
We also haven’t touched on any of the optional modules, that offer for example integrations with Guava and Scala.
The implementation of all these examples and code snippets can be found in the GitHub project – this is a Maven project, so it should be easy to import and run as is.