Fluent-API: Creating Easier, More Intuitive Code with a Fluent API

Otavio Santana
xgeeks
Published in
5 min readSep 10, 2021
Photo by Kaushal Subedi on Unsplash

We know that, in a software project, nothing replaces good documentation. However, it is also necessary to pay attention to how intuitive the written code is. After all, the simpler and more natural the code is, the better its experience for users.

In the simple “programming rule”, in which we will forget everything we have to remember, an API that “forces” you to remember is crucial proof of failure.

That’s why, in this article, we’ll introduce the topic and show you how to create a fluid API from the Fluent-API concept.

What is a Fluent-API?

When we speak in the context of software engineering, a fluent-API is an object-oriented API whose design is largely based on method chaining.

This concept, created in 2005 by Eric Evans and Martin Fowler, aims to increase code readability by creating a domain-specific language (DSL).

In practice, creating a fluent API means developing an API in which it is unnecessary to memorize the next steps or methods, allowing for a natural and continuous sequence as if it were a menu of options.

This natural cadence works in a similar way to a restaurant or even a fast-food chain in that as you are putting together a dish, the options vary according to the choices you make. If, for example, you choose a chicken sandwich, the sides will be suggested considering the chosen dish and so on.

Fluent API in Java context

In the Java world, we can think of two famous examples of this type of implementation.

The first one is the JOOQ framework, a project led by Lukas Eder, which facilitates communication between Java and relational databases. JOOQ’s most significant difference is that it is data-oriented, which helps avoid and/or reduce the impedance problem, or loss, associated with relational and object-oriented.

Another example is in non-relational databases, i.e., NoSQL, within the specifications of the enterprise Java world. Among them is Jakarta EE, which is the first specification of its kind and which became Jakarta NoSQL under the umbrella of the Eclipse Foundation.

The purpose of this specification is to ensure smooth communication between Java and NoSQL databases.

Generally speaking, a fluent API is divided into three parts:

  1. The final object or result: Overall, the fluent-API resembles the builder pattern, but the most powerful dynamic is coupled with DSL. In both, the result tends to be an instance representing the result of a process or a new entity.
  2. The options: in this case, are the collections of interfaces or classes that will serve as “our interactive menu”. From an action, the idea is that show only the options available for the next step, following an intuitive sequence.
  3. The result: after all this process, the answer may or may not result in an instance either for an entity, strategy, etc. The critical point is that the result must be valid.

Fluid API in practice

To demonstrate some of this concept, we’ll create a sandwich order with the expected result of an order with the corresponding purchase price. The flow will be as shown below.

Of course, there are several ways to implement this fluent API functionality, but we opted for a short version.

As we already mentioned the three parts of an API — object, options, and result -, we will start with the order that the “Order” interface will represent. A highlight is that this interface has some interfaces, which will be responsible for demonstrating our options.

The result of this API will be our order class. It will contain the sandwich, the drink, and their respective quantities.

A quick add-on before we go back to the tutorial

One point that we won’t focus on in this article, but that is worth mentioning, is related to the representation of money.

When it comes to numerical operations, it is ideal to use BigDecimal. That’s because, following references like the Java Effective book and the blog When Make a Type, we understand that complex types need a unique type. This reasoning, coupled with the pragmatism of “don’t repeat yourself” (DRY, or don’t repeat yourself), the result is the use of the Java specification for money: The Money API.

The last step in the journey is API implementation. It will be responsible for the “ugly” part of the code, making the API look beautiful.

The price list will be placed directly in the code since we don’t use a database or another data reference, and we intend to make the example as simple as possible. But it is worth stressing that, in a natural environment, this information would be in a database or a service.

The result is an API that will return the request to us straightforwardly and intuitively.

How is Fluent API different from others patterns?

It is widespread to have a comparison between two API standards, which are Builder and Fluent-API. The reason is that they both use methods in sequence for the process of creating an instance.

However, Fluent-API is “tied with a DSL”, and it forces an easy path to do so. But to make these differences even more evident, we’ve separated highlights for each of these patterns:

The Builder pattern:

  • It tends to be much easier to implement;
  • It is not clear which construction methods are needed;
  • The vast majority of problems will happen at runtime;
  • Some tools and frameworks create it automatically;
  • It needs more robust validation in the build method to check which mandatory methods were not invoked.

The Fluent-API:

  • It is important that, for each method, there is validation and throws the error if the parameter is invalid, remembers the fast fail premise;
  • It must return a valid object at the end of the process.

And now, is it easier to understand the similarities and differences between patterns?

That is our introduction to the concept of fluent-API. As with all solutions, there is no “silver bullet”, as great complexity is often not justified for the entire process.

Our colleague Rafael Ponte often says that “the easier it is to use the API for the client, the more difficult it will be to design and implement it for the developer”.

It is an excellent tool that helps in creating a failsafe for you and other users. You can see more about it on Sou Java’s Github.

If you enjoy working on large-scale projects with global impact and if you like a real challenge, feel free to reach out to us at xgeeks! We are growing our team and you might be the next one to join this group of talented people 😉

Check out our social media channels if you want to get a sneak peek of life at xgeeks! See you soon!

--

--

Otavio Santana
xgeeks
Editor for

Empowering developers worldwide to deliver better software in the Cloud. Staff Eg xgeeksio