adding an “and” method when using Fluent Design

The Fluent design (or fluent interface) makes code easier to read (and write). For those that are not familair 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 StringBuilder:

StringBuilder builder = new StringBuilder();
  builder.append("this").append("that").append("etc");

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 and method to my fluent interface:

public Job and(){
  return this;
}

Now the code reads much better:

job.addThis().and().addThat()
  • Share/Bookmark

About this entry