1. Overview

In this tutorial, we’ll discuss the fluent interface design pattern and we’ll compare it to the builder pattern. As we explore the fluent interface pattern, we’ll realize that the builder is just one possible implementation. From there, we can delve into best practices for designing fluent APIs, including considerations like immutability and the interface segregation principle.

2. Fluent Interface

The Fluent Interface is an object-oriented API design that allows us to chain method calls together in a readable and intuitive manner. To implement it, we need to declare methods that return objects from the same class. As a result, we’ll be able to chain together multiple method calls. The pattern is often used in building DSLs (Domain-Specific Languages).

For example, Java8’s Stream API is using the fluent interface pattern and allows users to manipulate streams of data in a very declarative way. Let’s look at a simple example and observe how, after each step, a new Stream is returned:

Stream<Integer> numbers = Stream.of(1,3,4,5,6,7,8,9,10);

Stream<String> processedNumbers = numbers.distinct()
  .filter(nr -> nr % 2 == 0)
  .skip(1)
  .limit(4)
  .map(nr -> "#" + nr)
  .peek(nr -> System.out.println(nr));

String result = processedNumbers.collect(Collectors.joining(", "));

As we can notice, firstly we need to create the object implementing the fluent API pattern, in our case, this is achieved through the static method Stream.of(). After this, we manipulate the through its public API, we can notice how each method is returning the same class. We finish with a method that returns a different type, ending the chain. In our example, this is a Collector that returns a String.

3. The Builder Design Pattern

The builder design pattern is a creational design pattern that separates the construction of a complex object from its representation. The Builder class implements the fluent interface pattern and allows for the step-by-step creation of objects.

Let’s look at a straightforward usage of the builder design pattern:

User.Builder userBuilder = User.builder();

userBuilder = userBuilder
  .firstName("John")
  .lastName("Doe")
  .email("[email protected]")
  .username("jd_2000")
  .id(1234L);

User user = userBuilder.build();

We should be able to recognize all the steps discussed in the previous example. The fluent interface design pattern is implemented by the User.Builder class, which is created using the User.builder() method. After this, we are chaining multiple methods calls, specifying various attributes of the User, each of these steps returning back the same type: a User.Builder. Finally, we exit the fluent interface through the build() method call, which instantiates and returns User. As a result, we can safely say that the builder pattern is the only possible implementation of the fluent API pattern.

4. Immutability

If we want to create an object with a fluent interface, we need to consider the immutability aspect. The User.Builder from the previous section was not an immutable object, it was changing its internal state, always returning the same instance – itself:

public static class Builder {
    private String firstName;
    private String lastName;
    private String email;
    private String username;
    private Long id;

    public Builder firstName(String firstName) {
        this.firstName = firstName;
	return this;
    }

    public Builder lastName(String lastName) {
        this.lastName = lastName;
	return this;
    }

    // other methods

    public User build() {
         return new User(firstName, lastName, email, username, id);
    }
}

On the other hand, it is also possible to return a new instance each time, as long as they have the same type. Let’s create a class with a fluent API that can be used for generating HTML:

public class HtmlDocument {
    private final String content;

    public HtmlDocument() {
        this("");
    }

    public HtmlDocument(String html) {
        this.content = html;
    }

    public String html() {
        return format("<html>%s</html>", content);
    }

    public HtmlDocument header(String header) {
        return new HtmlDocument(format("%s <h1>%s</h1>", content, header));
    }

    public HtmlDocument paragraph(String paragraph) {
        return new HtmlDocument(format("%s <p>%s</p>", content, paragraph));
    }

    public HtmlDocument horizontalLine() {
        return new HtmlDocument(format("%s <hr>", content));
    }

    public HtmlDocument orderedList(String... items) {
        String listItems = stream(items).map(el -> format("<li>%s</li>", el)).collect(joining());
        return new HtmlDocument(format("%s <ol>%s</ol>", content, listItems));
    }
}

In this case, we’ll obtain an instance of our fluent class by calling the constructor directly. Most methods are returning a HtmlDocument and complying with the pattern. We can use the html() method to end the chain and get the resulting String:

HtmlDocument document = new HtmlDocument()
  .header("Principles of O.O.P.")
  .paragraph("OOP in Java.")
  .horizontalLine()
  .paragraph("The main pillars of OOP are:")
  .orderedList("Encapsulation", "Inheritance", "Abstraction", "Polymorphism");
String html = document.html();

assertThat(html).isEqualToIgnoringWhitespace(
  "<html>"
  +  "<h1>Principles of O.O.P.</h1>"
  +  "<p>OOP in Java.</p>"
  +  "<hr>"
  +  "<p>The main pillars of OOP are:</p>"
  +  "<ol>"
  +     "<li>Encapsulation</li>"
  +     "<li>Inheritance</li>"
  +     "<li>Abstraction</li>"
  +     "<li>Polymorphism</li>"
  +   "</ol>"
  + "</html>"
);

Furthermore, since HtmlDocument is immutable, each method call from the chain will result in a new instance. In other words, a document with a header will become a different object if we append a paragraph to it:

HtmlDocument document = new HtmlDocument()
  .header("Principles of O.O.P.");
HtmlDocument updatedDocument = document
  .paragraph("OOP in Java.");

assertThat(document).isNotEqualTo(updatedDocument);

5. Interface Segregation Principle

The Interface Segregation Principle, the “I” in SOLID, teaches us to avoid large interfaces. To fully comply with this principle, a client of our API, should not depend on any methods it never uses.

When we build fluent interfaces, we have to keep an eye on our API’s number of public methods. We can be tempted to add more and more methods, resulting in a huge object. For example, the Stream API has more than 40 public methods. Let’s take a look at how the public API of our fluent HtmlDocument can evolve. To preserve the previous examples, we’ll create a new class for this section:

public class LargeHtmlDocument {
    private final String content;
    // constructors

    public String html() {
        return format("<html>%s</html>", content);
    }
    public LargeHtmlDocument header(String header) { ... }
    public LargeHtmlDocument headerTwo(String header) { ... }
    public LargeHtmlDocument headerThree(String header) { ... }
    public LargeHtmlDocument headerFour(String header) { ... }
    
    public LargeHtmlDocument unorderedList(String... items) { ... }
    public LargeHtmlDocument orderedList(String... items) { ... }
    
    public LargeHtmlDocument div(Object content) { ... }
    public LargeHtmlDocument span(Object content) { ... }
    public LargeHtmlDocument paragraph(String paragraph) { .. }
    public LargeHtmlDocument horizontalLine() { ...}
    // other methods
}

There’re many solutions to keep the interface smaller. One of them would be to group the methods and compose the HtmlDocument from small, cohesive, objects. For instance, we can limit our API to three methods: head(), body(), and footer(), and create the document using object composition. Notice how these small objects expose a fluent API themselves

String html = new LargeHtmlDocument()
  .head(new HtmlHeader(Type.PRIMARY, "title"))
  .body(new HtmlDiv()
    .append(new HtmlSpan()
      .paragraph("learning OOP from John Doe")
      .append(new HorizontalLine())
      .paragraph("The pillars of OOP:")
    )
    .append(new HtmlList(ORDERED, "Encapsulation", "Inheritance", "Abstraction", "Polymorphism"))
  )
  .footer(new HtmlDiv()
    .paragraph("trademark John Doe")
  )
  .html();

6. Conclusion

In this article, we’ve learned about fluent API design. We explored how the builder pattern is just one implementation of the fluent interface pattern. Then, we delved deeper into fluent APIs and discussed the problem of immutability. Finally, we tackled the problem of large interfaces and we learned how to split our API to comply with the Interface Segregation Principle.

The full code used in this article can be found over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.