The latest expert opinions, articles, and guides for the Java professional.

A Fluent API or not a fluent API? That is the Question!

Fluent API or not?

Nowadays with the variety of programming languages available to you, it’s tough to stick to the coding rules of your favorite choice without looking at what else is available.

I have been a professional Java developer for many years now, but I’m keen to always look at what is being done in the industry by all kinds of actors and I have to admit to something: there is cool stuff out there, in other programming languages. The cool stuff isn’t just the features or syntactic sugar constructs, but it’s also the coding standards that get my attention. In this post I want to talk about fluent APIs.

For the first 19 years of its life, Java hasn’t been a particularly fluent language and a lot of developers we’re quite vocal about that. I don’t know how many times I’ve heard the words “verbose” and “Java” in the same sentence, but believe me, it’s more than I care to count. I tend to agree with that sentiment, by the way, but rather than just complain about it, I decided to share my thoughts on how you can write a fluent API in Java. Warning, some of these thoughts do not follow the normal Java coding styles, rules, standards. So if you’re a Java purist, you may want to hide under your desk at this point.

In this post I would like to discuss the concepts and patterns that are often used in Java, and discuss whether or not it would be a good idea to avoid them to achieve a fluent API.

Java is verbose, what about other languages?

As I previously mentioned, Java is a verbose language. But I thought I’d repeat it to increase the verbosity of this blog post! Maybe Java’s verbosity is one of the reasons why so many new JVM languages were created, but during this post, I will also venture off of the JVM platform as well. For now though, we’ll start with a familiar JVM language for most.


Having used Gradle in my projects for a while now, I’m familiar with Groovy as the it’s the DSL which the Gradle build tool is built on. Groovy is a very expressive language without needing to write an awful lot of code. Let’s start with the simplest case:

If we go a little deeper, one of the features I particularly like is String interpolation (or variable expansion).

There’s just no need for a heavyweight StringBuilder! Is that enough evidence to call Groovy fluent? Well, not with just these examples, but how about if we use closures?

This code is taken from a gradle build script of SlideshowFX. Basically, it takes a configuration, named markdown, collects the name of every artifact (e.g. dependencies) and creates a comma separated string with that data, with a period to finish. The result is the following:

I find this a pretty fluent way of developing code, don’t you? Okay, it’s time to get our hands dirty, let’s talk JavaScript!


Web development is extremely popular, particularly compared to the “good old” rich clients (which I love so much, but that’s another story). With web development, comes JavaScript, which has played a key role. There are a lot of libraries available for you to use, some I’ve already talked about in a previous RebelLabs article about JavaScript confessions. These libraries allow to do some amazing things, from code highlighting to 3D rendering. There are so many libraries out there, the JavaScript syntax has needed to evolve and has in turn become very fluent, as has the JSON format which has been widely used. Let’s take a look:

The syntax will undoubtedly look very familiar to everyone and it’s very concise. When you use libraries like jQuery, you won’t be surprised to see examples to chaining methods in the code.

Java 8

Even when writing an article in which I ask you to review and look at other languages, I simply cannot ignore Java 8 which has many new features that have been widely praised by the Java community. Straight away, of course, you’ll think about the addition of Lambdas in the Java language. I have to admit: I like them. Groovy has Closures, Java has Lambdas. It completely changes the way we code and read code and it brings some much needed simplification to the language. See what you think:

As you can see from the snippet above, I have combined Lambdas with the Steam API, allowing you to traverse a collection in a very fast and efficient manner by turning complex computations into operations. Let’s look at a more complex example:

This snippet converts all items of the array into a Map using an Integer as a key and the number raised to the power of 2 as a value. Lambdas aren’t the only fluent API in Java 8. Don’t forget about the new, powerful and very fluent date and time API.

In comparison with the previous API, the new version is much more fluent and is largely inspired by Joda-Time.

Being fluent: where and why?

As seen previously, being fluent makes it easier for developers to adopt your API. But where should you be fluent and more to the point, why? Let’s try to answer these questions.

The JavaBean

The JavaBean concept is well known in the Java world and a lot of APIs rely on it. The rules for making a JavaBean are pretty simple:

  • Have a default constructor
  • Make every field private (or protected)
  • Use getters / setters to access each field

A simple example of a JavaBean is as follows:

Much in Java builds upon these elementary blocks. The EntityBean in JavaEE, for example, relies on this concept. For those who don’t know the concept, here’s a long story cut short: it’s an object (a Java class) representing an SQL table, or for those playing with Hibernate ORM, an entity stored within a data store. In a document oriented NoSQL data store, like MongoDB, it would be a JSON structure. But the exact implementation is not important. The point is that in order to persist and retrieve an EntityBean to and from a storing engine, JPA performs some operations:

  • Every non transient value of an EntityBean is persisted using the getXXX method.
  • Every value retrieved from the storing engine is set on an EntityBean using the setXXX method.

Moreover, the JDK itself relies on this concept in order to find getters and setters methods of a bean. When you are doing some reflection in Java, it is pretty easy to get a getter and setter method from a field’s name, and then, invoke it. Let’s play a bit:

And if you want all getters and setters:

At this point, there’s no problem but you can see what’s coming: what if I refactor the Foo class a little bit:

This improvement allows me to write the following code:

We call this method chaining. We now have a problem, because if we try to get the setter method using the previous technique, you will get a java.beans.IntrospectionException: Method not found: setBar. So don’t even think about refactoring the Foo class that way. Instead consider the following code:

And invoke as follows:

So what should we do with the JavaBean concept? Should we break free of it to make our APIs and code more fluent or just live with it? Considering a lot of APIs rely on it I don’t think breaking it is the right path, particularly because the next concept provides a better solution.

The factory/builder pattern

Basically, a factory is class that has a static method for building an object of a given type. The type of the factory is not of the same as the object it is building. For example, in Java you have (among others) the ProcessBuilder class that builds Process objects. This is particularly useful when the object you are trying to build is complex and you want to avoid your API’s users to know about and handle the boilerplate code needed for your API. This is paramount if it requires:

  • a lot of skill
  • a lot of configuration
  • a lot of parameters
  • to specify JNI libraries

Be warned, a factory will not resolve everything because your API is complex. A good refactoring would actually be much better, maybe mandatory, but I digress. So, the factory pattern is well suited in providing a fluent mechanism to build objects. Typically, we could use a minimal example:

In the JDK you can find the Calendar#getInstance() method that is similar to the previous example, among others.

The Context JavaBean

This is a concept of mine which consists of creating a JavaBean, which does not respect the fundamentals of a JavaBean. The Foo class described previously is a typical example.

These objects are particularly useful when used as context when calling a method. In some cases I like to provide a contextual object to a method instead of having a long list of parameters for that method. This allows me to add parameters to a method by avoiding method chaining in its declaration. Let’s see an example:

If I need more parameters I just need to update the contextual bean. In the case of a contextual object, I like to write a fluent API because I know those beans will never be serialized and only ever be used as helper objects.

How Do the Professionals Do It?


If you take a look at the jOOQ library, you will discover a very good example of a fluent API. For writing an SQL query using jOOQ, you can write something like this:

In this particular case, a fluent API shows one of its great potential by abstracting the Object language to be as fluent as the SQL grammar by:

  • facilitating the query writing;
  • avoiding typos.

Just let me explain the first bullet point. On the one hand, skilled SQL developers will use the API as fluent as if they were writing plain SQL text in their editor, and very quickly thanks to modern autocompletion provided by IDEs. On the other hand, newcomers to SQL (are there any?) will be helped to avoid mixing instructions, like putting a WHERE clause before the FROM one. Indeed, when they perform a select(…) operation, the API returns an object that doesn’t contain a where(…) method for example.


Vert.x is also a library that is very fluent. In order to get an instance of Vert.x, you do the following:

Additionally, the library takes care of creating the instance correctly. Also in Vert.x, you have the possibility to specify routes that are allowed using a Router. The router can be configured as follows:


In the fun world of lightweight Java frameworks for creating web applications, Spark is very fluent when it comes to creating a server and configuring it. It is inspired by Sinatra. Let’s see an example:

As you can see, using Spark completely hides the server instantiation by simply making you configure the server and the resources it serves. This lets you focus on the business you want to provide rather than the configuration. It is a paradigm I would call “Implementation over Configuration”.


To summarize there are cases of being fluent and cases of not being fluent. The worst time to create a fluent API is a JavaBean that need to be serialized, to a database for instance, because of the high risk of breaking compatibility between libraries relying on the fundamentals of Java. A better solution would be to create a contextual JavaBean.

Another great alternative is to use factories and builders using a fluent API to hide the more complex boilerplate of the class instantiation.

Fluent APIs are very beneficial when creating integrations between different languages such as Java and SQL, like jOOQ provides. But it also helps you to avoid errors, like typos, when writing code. Additionally, it provides you with a subtle mechanism to direct a user in how to use your API, by returning specific objects when a particular method is used. Think of the jOOQ API and its use of select, from, where clauses.

Do you have an example of a good Java project with an impeccably fluent API? Let me know below in the comments or tweet me: @twasyl.

Read next:

Responses (14)

  1. Avatar  

    Rafael Chaves

    December 9, 2015 @ 12:39 pm

    In the section on Groovy, shouldn’t “how about if we use Clojure” be “how about if we use closures”?

  2. Avatar  

    Oleg Šelajev

    December 9, 2015 @ 5:32 pm

    That’s true! And not surprisingly, that’s my fault rather than Thierry’s. Thanks for telling us, fixed now!

  3. Avatar  

    Lukas Eder

    December 15, 2015 @ 8:33 am

    I just wish the Java compiler allowed for chaining method calls on all void methods. That would already remove a lot of unnecessary boiler plate code in APIs.

  4. Avatar  

    Thierry Wasylczenko

    December 15, 2015 @ 3:08 pm

    You are welcome for mentioning jOOQ, well deserved!

  5. Avatar  


    December 16, 2015 @ 9:56 am

    So much love for FluentAPI, almost declarative!

    I think the general problem with the JavaBeans is the wrong concept of property, you can’t rely on setters and getters, since they are not properties at all, they are functions (not pure methods, since they always return something, void is something as well ;) ) and you can do whatever you want with them.

    I don’t know if allowing chaining method on void functions is a good thing as @Lukas Eder:disqus wished, I mean I can understand it if they were properties, but not on void functions. And about void functions, since they are functions I think it’s better to return always something much more useful than ‘void’.

    An aspect I didn’t find in the article: if I’m not wrong for the next JEE8 such concept of getting the state of an object will change, no more JavaBean properties, since the state will be «evaluated» by using the inner fields, am I right? something that some libraries already do (for instance Gson).

  6. Avatar  


    December 18, 2015 @ 10:01 pm

    One thing that needs to be discussed is extending Java classes that provide fluent API. This is a fairly complex topic, but the executive summary if that Java language effectively blocks one from proving fluent API for classes that are meant to be extended.

    Reason is that one would 1) either have to override super class fluent API to change return types to subclass 2) or use generics to pass that information. In the first case extending a class would become very hard. In the latter the use of those classes would become ugly.

    This is a _major_ roadblock for Vaadin team. We really would love to provide fluent API everywhere, but there seems to be no working solutions.

    Anyone knows a solution for this?

    The only user friendly solutions that I can think of would rely on tooling generating fluent API as aspects. But I would not want to rely on AspectJ or similar, nor be limited to use some specific tooling.

    Thierry, I would encourage to post a part II were extension problem is discussed.

  7. Avatar  

    David Leppik

    December 18, 2015 @ 10:10 pm

    Concerning getters/setters rather than raw access to properties:

    When Java was still new, Object Oriented gurus insisted that this was best practice. (They still do.) The general rule in OO design is that data is hidden, and only reluctantly revealed by telling an object to perform an action.

    The general thinking at the time was that objects are big, heavyweight, stateful things for organizing big chunks of code. Example objects from OO books at the time had either big-thing names (e.g. “…Service”) or silly names (“Animal”, “Cow”). None of them existed primarily to store data. And therefore revealing anything about the data–and therefore the actual implementation– was discouraged.

    Of course, it turns out that many, if not most, classes exist solely to store/organize data. Hence getters and setters. Sun recognized this by introducing JavaBeans, but because they only changed the API and not the grammar, you end up with tons of boilerplate. Worse, now “get” and “set” came to mean “there’s a variable with this name, so we might as well have just exposed it.”

    Scala does it better. It applies the same OO practice (reading properties and calling parameterless functions are exposed with the same API). In Scala, an immutable property can override a parameterless function.

    Kotlin does it even better. It has data classes, which are intended to store and organize data. And they are immutable, and therefore stateless, so you don’t need setters or anything else that might muck things up. (Consider that calling a setter usually changes an object’s hash, and often its sort order, meaning it’s now misfiled if it’s in a Set or Map.) Thus you can cleanly separate classes that do stuff from classes that know stuff. (Scala almost has this, through case classes.)

    Fluent APIs really go hand-in-hand with immutable/stateless objects. Having “set” return “this” isn’t intuitive. It makes just as much sense to have it return the old value. Whereas with stateless classes it makes perfect sense. Consider (Java 8) Instant.plusSeconds(3) or MonthDay.withMonth(April). It’s obvious what the result is, and reasonable to guess that the original object is unchanged.

  8. Avatar  

    Thierry Wasylczenko

    December 27, 2015 @ 1:47 pm

    Hi there,

    Thank you for giving your opinion.
    I totally get the point that classes’ members are not properties. Getters/setters shouldn’t be as simple as we saw/code it most of the time. They can be used to perform some validation before setting a value. For example when you call a setter for a member representing a distance, you may want to ensure it’s not a negative value. This might be an argument in flavor of having a setter instead of changing the member’s visibility.

    I don’t know if you can easily perform validation when setting a property’s value in other languages like groovy, Scala or even Kotlin. Do you have some feedback or best practices to share? :-)

  9. Avatar  

    Thierry Wasylczenko

    December 27, 2015 @ 1:58 pm

    Hi there,

    Thanks for giving your opinion. You just succeed in keeping me curious about Kotlin that I haven’t tried yet and that I _need_ to find some time to have a look at it.

    Regarding Java 8 and the date/time API I may not share entirely your opinion sorry. The result of XXX.plusYYY(…) is indeed obvious but some developers could think it affects the current instance and return it. I have to admit I’m and when I am using a fluent API it is the behavior I expect for two main reasons:
    1/ I don’t want/need to store the result into a new variable
    2/ I think that always returning a new instance can have memory impacts. Typically in some case I need to have the most little memory footprint possible and each time you call the method of Instant you get a new Instant. And everybody knows how hard it is to optimize the garbage collector in Java. But I think that maybe it’s not Java I should use in that case ;-)

    But again very thank you for explaining how other languages manage that topic, I always like to know what others do it.

  10. Avatar  

    Thierry Wasylczenko

    December 27, 2015 @ 2:15 pm

    Hi there,

    Thank you for giving your opinion. You just hit a difficult topic by mentioning maintainability of a fluent API. I don’t know if it is a good practice to override a method in subclasses, at least if you call super. But I would say it really depends of the use case because in some situations you may want to totally ignore the super computation. I would recommend using a factory/service/helper class for building the final object. And that class should handle all the boilerplate for maintaining the correct way of building the object. Because as you say, you can inject some generics in the loop, but just let admit it: generics in Java become very quickly ugly and totally misunderstood :-) So that starts the debate about choosing fluent API versus readable code ;-)

    Regarding the fact you would provide everywhere a fluent API in Vaadin: maybe that’s not a good idea. I think that there are cases that are best candidates for such an API, but in others, if you _really_ don’t find a way of doing it or if you do and it doesn’t suits you, maybe you should just do it the best way you can :-) The reason I’m saying this is that when I develop something I always ask myself how would be the best way of doing it, questioning myself for a long time, reading blog posts, asking friends advices, and sometimes I just have to admit that I can’t find a better way that the one I found. But I keep it in mind for the next version because software development evolves so fast as well as languages, so I will always have the opportunity to find a new way.

    Thank you very much for your contribution and encouragement for another article. Let’s keep in touch.

  11. Avatar  


    December 27, 2015 @ 6:53 pm

    Well it’s just my personal point of view but when we talk about «values» of an object, it sounds that we talk about them as they were something unbound with the object state itself, but it’s not. Let’s take an example in case of immutable objects:

    public class Person {
    private final String name;
    private final Integer age;

    public Person(final String name, final Integer age) { = name;
    this.age = age;

    public final String name() { return; }
    public final Integer age() { return this.age; }

    when we create an object like this: new Person(“Donald Duck”, -12) we always create a valid object, no matter what. There’s no issue with that. However is it right one for our application logic? Maybe not since we want a positive number for the Age and a name size greater than 8 characters and lesser than 120.

    Then we need to create a specification for that, just as the Specification/Criterion Pattern suggests. Much much better in my opinion than any validation in the setters, since that object must be a model without containing any logic and most of all you check the object state against your application logic, not the values.

    The «setters» (but as I said before I think it’s better to forget about the usual ones) should retrieve a new instance of the object with the current state merged the modified value:

    public class Person {

    public final Person age(final Integer age) { return new Person(, age); }


    although it should be named with the name of an action, not the field name itself.

    In the case of mutable objects everything it’s little bit easier, but it always depends on the kind of application you’re building.

  12. Avatar  

    Thierry Wasylczenko

    December 29, 2015 @ 8:24 am

    I totally agree with the Specification/Criterion pattern as well as with the fact the JavaBean should stay business agnostic. The validation suggestion in the setter was an example.

    Regarding a new instance returned by the setter, as said in another comment, I’m not sure it’s a good idea in terms of memory consumption. It could quickly become a nightmare in my opinion. Just imagine the number of instances that would be created by an ORM :-(

    It also depends if we consider our objects to evolve in our business logic or just represent a state at a moment (just think about caches). But as you mentioned, it’s all a matter of what application we build!


  13. Avatar  


    February 23, 2016 @ 5:45 pm

    Just use Clojure and any API will be fluent

  14. Avatar  


    May 14, 2016 @ 6:28 am

    Great article. In the world of Java, I think that we have also forgotten that Methods are in fact Functions or Procedures. In most languages, like Java & C, these differ only on the key aspect of the void/return types difference. The Procedural Identity is not something that should be lost – it serves a purpose in its own right. That identity might be lost in a Chaining outcome depending on how such is structured and implemented.

    The builder or context object solutions are the right ones I believe, not chaining void methods.

RSS feed for comments on this post.

Leave a comment