Fluent Java APIs

Good morning!

Yesterday, I wrote a parody post about Yours Truly.

I stated that OOP and FP are basically the same — and I meant it. But you may have recognized that my example was an easter egg.

 * Search and destroy that 🐜

interface Ant {
    // properties omitted

interface Poison {
    Ant apply(Ant ant);

final class Search {

    // omitted private constructors and instance vars

    static Search of(Criteria criteria) {
        return ...;

    Ant destroy(Poison poison) {
        return poison.apply(ant);

At the use-site we would call it this way:

// 💣 something unexpected may happen...
Ant ant = Search.of(antCriteria).destroy(poison);

But the API has a caveat. What if our the Search is not successful, i.e. no ant could be found? Then we also cannot apply the poison to that ant and the result is undefined (resp. null).

There also could occur errors during search or poison application. Or the search could take a very long time because the ants hide very well.

I want to elaborate a bit on how we would solve such problems with VAVR without introducing a custom DSL. Instead we use the existing VAVR DSL.

Example 1: No search result

// search strategy
Option<Ant> search(Criteria criteria);

// use-site
Option<Ant> ant = search(antCriteria).map(poison::apply);

Example 2: Failed search or poison application

// search strategy
Try<Ant> search(Criteria criteria);

// use-site
Try<Ant> ant = search(antCriteria).map(poison::apply);

Example 3: Long running search

// search strategy
Future<Ant> search(Criteria criteria);

// use-site
Future<Ant> ant = search(antCriteria).map(poison::apply);

The above examples reflect the main idea of the VAVR API. We soleily concentrate on the implementation of the business logic, in this case the search strategy. The VAVR types help us to express common scenarios, like failures, absence of results or asynchronous results.

Compared to native Java, VAVR has a small API surface area — we do not need to learn many vocabulary. Different types integrate well with other APIs. Namely, nearly all types implement Iterable and are convertible to other Java and VAVR types.

Holiday greets from Yours Truly!