Sunday, September 25, 2016

Combinator Pattern with Java 8

The Combinator Pattern is well known in functional programming. The idea is to combine primitives into more complex structures. At my last talk at the majug I presented a way of how to employ this pattern with Java 8. In this post we will have a look at this design.

Before we start

If you know functions and higher-order functions in Java 8, then you are more than prepared to read this post. If not, I recommend you to look at this presentation. There you will find a nice introducution to functions in Java 8 by Artem. The code can be found here.

On primitives and combinators

Like many constructs in functional programming, primitives and combinators are names for abstractions. Wikipedia provides a description for language primitives:

In computing, language primitives are the simplest elements available in a programming language. [...] an atomic element of an expression in a language.
-- Wikipedia

Likewise, primitives used in the combinator pattern are the simplest elements within a domain. For example, addition and multiplication in the domain of integers. Combinators provide means to compose primitives and/or already composed structures into more complex structures. For example, combining multiplication and addition. Due to the declarative nature of this pattern, the code itself employs a lot of domain terms.

Validation with combinators

Let's pretend we are tasked to validate users. A user is valid if the name is not empty and the email contains an @ sign. A straight-forward way to model this, is to add query methods to the corresponding entity:

public class User{
   public final String name;
   public final int age;
   public final String email;

   public User(String name, int age, String email){
     this.name = name;
     this.age = age;
     this.email = email; 
   }

   public boolean isValid(){
     return nameIsNotEmpty() && eMailContainsAtSign();
   }

   private boolean nameIsNotEmpty(){
     return !name.trim().isEmpty();
   }

   private boolean eMailContainsAtSign(){
     return email.contains("@");
   }
}

new User("Gregor", 30, "nicemail@gmail.com").isValid(); // true

While this reads well, there are some disadvantages. What happens when the validation rules change? For example, for some use cases users must be older than 14. In this case, we need to adapt the isValid method. So this looks like a violation of the SRP. Before we refactor and extract the validation part into an own class, let us sit back and think about what we want to express.

A user is valid if and only if a given set of rules are satisified. A rule describes the properties a user must have. Different rules can be combined to more complex ones. Applying a rule yields a validation result which describes the outcome. For now, let us assume that a true boolean value indicates that a user is valid. In more functional terms, we can express this in the following way:

public interface UserValidation extends Function<User, Boolean>{}

UserValidation nameIsNotEmpty = user -> !user.name.trim().isEmpty();
UserValidation eMailContainsAtSign = user -> user.email.contains("@");
User gregor = new User("Gregor", 30, "nicemail@gmail.com");

nameIsNotEmpty.apply(gregor) && eMailContainsAtSing.apply(gregor); // true

There is some boilerplate code here. Why do we have to create the nameIsNotEmpty and eMailContainsAtSign rules by ourselves? Why do we have to combine the results manually? Why are there 4 lines of initialization code for just one application line?

Although the code is a bit wordy, it contains all building blocks for the combinator pattern: nameIsNotEmpty and eMailContainsAtSign are primitives and && is a combinator. With Java 8 we are able to move primitives and combinators into the UserValidation type.

interface UserValidation extends Function<User, Boolean> {
    static UserValidation nameIsNotEmpty() {
        return user -> !user.name.trim().isEmpty();
    }

    static UserValidation eMailContainsAtSign() {
        return user -> user.email.contains("@");
    }

    default UserValidation and(UserValidation other) {
        return user -> this.apply(user) && other.apply(user);
    }
}

User gregor = new User("Gregor", 30, "nicemail@gmail.com");
nameIsNotEmpty().and(eMailContainsAtSign()).apply(gregor); // true

Primitives are translated to static methods and combinators to default methods. Both primitives, nameIsNotEmpty and eMailContainsAtSign, return a lambda expression with UserValidation as target type. Different to primitives, the and combinator composes UserValidations by using the && operator.

There are two important observations in using this pattern. First, there is no application during combining time. This means, one first constructs a UserValidation and then executes it. This distinction makes one UserValidation applicable for many users. Second, UserValidation has no own state. This means, one UserValidation can be applied in a parallel environment without race conditions. For example, the following code conducts user validations in parallel.

List<User> users = findAllUsers()
    .stream().parallel()
    .filter(nameIsNotEmpty().and(eMailContainsAtSign())::apply) // to Predicate
    .collect(Collectors.toList());

Validation result reasoning

Continue reading %Combinator Pattern with Java 8%


by Gregor Trefs via SitePoint

No comments:

Post a Comment