What’s the fluent interface design pattern? It’s a design pattern which became very visible in recent time, mainly due to jQuery, which was designed around it. In this pattern, class methods return the same object they were called on (they end with “return this;”), which makes it possible to chain them. It also makes it easily spottable in code, due to the distinctive outline created by chained methods.
Let’s have a quick look at what I’m talking about.
If Java Swing libraries supported this kind of coding, then the following block of java code, copied from a random blog post, could be rewritten from this repetitive sequence:
JFrame mainFrame = new JFrame("Hello World");
mainFrame.add(label, BorderLayout.CENTER);
mainFrame.addWindowListener(new MainFrameListener());
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
…to this chain of methods:
new JFrame("Hello World")
.add(label, BorderLayout.CENTER)
.addWindowListener(new MainFrameListener())
.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
.pack()
.setLocationRelativeTo(null)
.setVisible(true);
It’s amazing how much cleaner the code looks just by eliminating all those mainFrame references.
But wait… doesn’t this look familiar from somewhere? Doesn’t it remind you of a certain language feature you may have used years ago?
Yes, you’re right! It looks remarkably like the “with” control structure available in Delphi/Pascal and VisualBasic! If Java also supported it, the above example could be rewritten like this:
with (new JFrame("Hello World")) {
add(label, BorderLayout.CENTER);
addWindowListener(new MainFrameListener());
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
It looks almost almost exactly the same as the one using the fluent interface, doesn’t it?
The main difference is that such a built-in construct works with any object you happen to throw at it, doesn’t require any additional effort from the library designer, and doesn’t require you to write repetitive code or wrapper classes if the library author failed to include the fluent interface pattern into the library in the first place. It also doesn’t interfere with the command-query separation principle and is perfectly compatible with step through debuggers.
But the fluent interface pattern does make it possible for us to have a special name for a simple concept, a Wikipedia entry for it, and dozens of blog posts about a solution to a problem that’s been solved, in a better way, decades ago.

No related posts.

This whole fluent thingy is not about sparing a few characters and making up for the lack of the with statement. It’s about creating API that really allows expressing what you want in an (almost) fluent English style, orin other words creating a DSL. Have a look the jmock/hamcrest examples. E.g. this one is a JUnit+hamcrest one: assertThat(responseString, either(containsString(“color”)).or(containsString(“colour”)));
Though it really makes look java like LISPified English :)
Your statement may be true for some small number of fluent interface implementations, such as jQuery’s where the ‘query object’ is always the active object. However many fluent interface implementations will return a different object at times and then the next method call applies to that different object. The with keyword does not achieve this – it guarantees that each method executes on the object you defined in the with.
Here is a really simple example from Fowler’s work in progress book on DSL’s:
computer()
.processor()
.cores(2)
.i386()
.disk()
.size(150)
.disk()
.size(75)
.speed(7200)
.sata()
.end();
Do you see how noisy that would be if you were trying to achieve the same thing using the with keyword?
Sigh. Follow the link for a version with whitespace…
This is valid Java code:
# new JFrame(“Hello World”) {{
# add(label, BorderLayout.CENTER);
# addWindowListener(new MainFrameListener());
# setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
# pack();
# setLocationRelativeTo(null);
# setVisible(true);
# }};
But it’s not fluent, like StringBuffer’s append, just syntactic sugar that works for this particular case.
@Paul Batum: I believe that computer(), disk(), processor(), etc methods in your example could all still be returning the same object; calling them just changes its internal state. I encountered a similar example just yesterday, except that one was demonstrating how to build XML DOM trees.
@superfav: Oops. Maybe I shouldn’t have built my examples using the language I don’t do much programming in. I actually had to pause and think for a couple of moments to figure out why it worked. :-)
But I know from experience with other languages that many don’t support similar workarounds using anonymous classes and init blocks. Also, as you’ve already mantioned it yourself, you can’t do this if you get your object from a factory or try using an existing object…
For each of those methods to be callable on the same object, the computer class would have to expose a size method for setting the size of a disk, and a speed method for setting the speed of the processor. For reasons that are self-evident, expecting your user to call these methods on the computer class rather than on the disk and processor class is an amazingly awful idea.
Yes, it is an awful idea; but that’s the approach I’ve seen used in fluent interfaces.
Let’s take this command sequence from your example:
.i386()
.disk()
.size(150)
.disk()
.size(75)
.speed(7200)
You can see that disk() is called twice: after i386() and after size(). For this to be possible, both i386() and size() must either be returning the same object (which represents the whole computer) OR every class (processor, disk, …) exposes methods for adding the next hardware component of any type, which would basically give you several almost identical classes. But if that’s the case, you might just as well use a single class instead, because calling disk() on a processor object is just as awful as calling size() on a computer object.