A Nice API Design Gem: Strategy Pattern With Lambdas

With Java 8 lambdas being available to us as a programming tool, there is a “new” and elegant way of constructing objects. I put “new” in quotes, because it’s not new. It used to be called the strategy pattern, but as I’ve written on this blog before, many GoF patterns will no longer be implemented in their classic OO way, now that we have lambdas.

A simple example from jOOQ

jOOQ knows a simple type called Converter. It’s a simple SPI, which allows users to implement custom data types and inject data type conversion into jOOQ’s type system. The interface looks like this:

public interface Converter<T, U> {
    U from(T databaseObject);
    T to(U userObject);
    Class<T> fromType();
    Class<U> toType();
}

Users will have to implement 4 methods:
  • Conversion from a database (JDBC) type T to the user type U
  • Conversion from the user type U to the database (JDBC) type T
  • Two methods providing a Class reference, to work around generic type erasure
Now, an implementation that converts hex strings (database) to integers (user type):

public class HexConverter implements Converter<String, Integer> {

    @Override
    public Integer from(String hexString) {
        return hexString == null 
            ? null 
            : Integer.parseInt(hexString, 16);
    }

    @Override
    public String to(Integer number) {
        return number == null 
            ? null 
            : Integer.toHexString(number);
    }

    @Override
    public Class<String> fromType() {
        return String.class;
    }

    @Override
    public Class<Integer> toType() {
        return Integer.class;
    }
}

That wasn’t difficult to write, but it’s quite boring to write this much boilerplate:
  • Why do we need to give this class a name?
  • Why do we need to override methods?
  • Why do we need to handle nulls ourselves?
Now, we could write some object oriented libraries, e.g. abstract base classes that take care at least of the fromType() and toType() methods, but much better: The API designer can provide a “constructor API”, which allows users to provide “strategies”, which is just a fancy name for “function”. One function (i.e. lambda) for each of the four methods. For example:

public interface Converter<T, U> {
    ...

    static <T, U> Converter<T, U> of(
        Class<T> fromType,
        Class<U> toType,
        Function<? super T, ? extends U> from,
        Function<? super U, ? extends T> to
    ) {
        return new Converter<T, U>() { ... boring code here ... }
    }

    static <T, U> Converter<T, U> ofNullable(
        Class<T> fromType,
        Class<U> toType,
        Function<? super T, ? extends U> from,
        Function<? super U, ? extends T> to
    ) {
        return of(
            fromType,
            toType,

            // Boring null handling code here
            t -> t == null ? null : from.apply(t),
            u -> u == null ? null : to.apply(u)
        );
    }
}

From now on, we can easily write converters in a functional way. For example, our HexConverter would become:

Converter<String, Integer> converter =
Converter.ofNullable(
    String.class,
    Integer.class,
    s -> Integer.parseInt(s, 16),
    Integer::toHexString
);

Wow! This is really nice, isn’t it? This is the pure essence of what it means to write a Converter. No more overriding, null handling, type juggling, just the bidirectional conversion logic.

Other examples

A more famous example is the JDK 8 Collector.of() constructor, without which it would be much more tedious to implement a collector. For example, if we want to find the second largest element in a stream… easy!

for (int i : Stream.of(1, 8, 3, 5, 6, 2, 4, 7)
                   .collect(Collector.of(
    () -> new int[] { Integer.MIN_VALUE, Integer.MIN_VALUE },
    (a, t) -> {
        if (a[0] < t) {
            a[1] = a[0];
            a[0] = t;
        }
        else if (a[1] < t)
            a[1] = t;
    },
    (a1, a2) -> {
        throw new UnsupportedOperationException(
            "Say no to parallel streams");
    }
)))
    System.out.println(i);

Run this, and you get:
8
7
Bonus exercise: Make the collector parallel capable by implementing the combiner correctly. In a sequential-only scenario, we don’t need it (until we do, of course…).

Conclusion

The concrete examples are nice examples of API usage, but the key message is this: If you have an interface of the form:

interface MyInterface {
    void myMethod1();
    String myMethod2();
    void myMethod3(String value);
    String myMethod4(String value);
}

Then, just add a convenience constructor to the interface, accepting Java 8 functional interfaces like this:

// You write this boring stuff
interface MyInterface {
    static MyInterface of(
        Runnable function1,
        Supplier<String> function2,
        Consumer<String> function3,
        Function<String, String> function4
    ) {
        return new MyInterface() {
            @Override
            public void myMethod1() {
                function1.run();
            }

            @Override
            public String myMethod2() {
                return function2.get();
            }

            @Override
            public void myMethod3(String value) {
                function3.accept(value);
            }

            @Override
            public String myMethod4(String value) {
                return function4.apply(value);
            }
        }
    }
}

As an API designer, you write this boilerplate only once. And your users can then easily write things like these:

// Your users write this awesome stuff
MyInterface.of(
    () -> { ... },
    () -> "hello",
    v -> { ... },
    v -> "world"
);

Easy! And your users will love you forever for this.

11 thoughts on “A Nice API Design Gem: Strategy Pattern With Lambdas

  1. Hi Lukas,

    great article!

    Martin Odersky once said: “I personally find methods (…) that take two closures as arguments are often overdoing it.”

    I’ve taken that citation from this article, where a concrete case is discussed.

    Personally I also try to avoid more than one function argument if possible.

    Btw – Mario Fusco did a great translation from the classical, object oriented ‘Gang of Four’ patterns to functional patterns: from-gof-to-lambda.

    Greets,

    Daniel

    1. There’s no general rule. Usually, such methods are indeed overdoing it. But in this particular case, things are straightforward. You get a type with N functions, you pass N functions as that type’s constructor arguments.

  2. What about a little builder, that takes these individual items, returns an in-between type and eventually concludes to return the Converter? That way, you basically “name” the individual parts and the setup code is slightly easier to read.

    1. Sure, that’s another option. Personally, I don’t like the builder “pattern” for this particular use-case, as it mostly only exists because of the lack of named parameters in Java. Also, it’s a bit more work (you need more types) if you want to ensure that 4 out of 4 mandatory arguments are really passed. I mean, I know how this works of course, I “wrote the book”: https://blog.jooq.org/2012/01/05/the-java-fluent-api-designer-crash-course. But I’d really very much prefer to be able to use named (and possibly defaulted) parameters.

      1. Totally agree. It’s just for the time being you can either live with a comma separated list of functions *or* a builder API. The latter is definitely more work on the API designers side but pays off (and probably will for the next decade, if Java ever gets named params) :)

        1. Hey, if var is being discussed, I have hopes for named params :)

          Anyway, agree. It’s a tradeoff. Sometimes, the builder is worth it (especially as the number of args grows).

    1. Thank you. I would like to see more Ceylon versions for things written in Scala, Java, Kotlin. If Ceylon is good enough, that will gradually make people come to Ceylon.

    2. As mentioned on Twitter also, your “improvement” isn’t possible due to Ceylon’s generic type reification, but due to subtyping. If you subtype the Converter<String, Integer> type, explicitly binding the <T, U> type variables, the generated Java class will also contain all type information and the Class<?> references would no longer be needed.

      However, it would be a bit of a PITA to expect users of Converter to know this, and there would always be edge cases where this breaks, so better just provide the class literals (in Java).

  3. That”s great to reduce boilerplate code but how could you reference your lambda-expressed converted on configuration level? Could you create a static instance of a converter and use it? On the examples I found on the jooq documentation for forcedType, the converter param seems to be related to a class, not an instance

Leave a Reply