Adding an “and()”-method when using Fluent Design

Raphaël Parrée
Raphaël ParréePublished on

The Fluent design (or fluent interface) makes code easier to read (and write). For those that are not familiar with this: it means the methods of a class return "this", so that you can chain methods calls. A well known example in Java is the PrintStream (due to it implementing the Appendable interface):

PrintWriter out = System.out;
out.append("Ooops..").append("i always used to append" 
   + "to the std out")
  .println(", shame on me");

It just means that the append method implementation return "this" as opposed to void. This morning I was using such a design again, but found the readability not as good as it should be:

job.addThis().addThat()

So i decided to add a little method to my fluent interface, named and():

public Job and(){
    return this;
---

Now the code reads much better:

job.addThis().and().addThat()