Update based on the comments below: Just to clarify, this answer is not a judgement of whether the fluent pattern is generally good or bad, it's about a relative trade-off in the specific situation where it is used to modify a single mutable object.
I'd suggest re-evaluating the idea of using a fluent interface in the first place if the only goal is simply to send a series of messages to the same object.
Before fluent interfaces were popular, many programs using OO languages would be full of simple 'message passing' code, which while slightly verbose, made its intent absolutely 100% clear in that these methods are all modifying the same object:
ButtonWidget widget = new ButtonWidget();
widget.dimensions(100, 60);
widget.backgroundColour(Colour.BLUE);
widget.text("Click Me!");
Is there anything wrong with that aside from the fact that the variable widget
appears on multiple lines? There's no ambiguity about other objects being created in memory, and having the variable there multiple times is not hurting readability at all - in fact, it's adding useful context in making it 100% clear that all these messages are indeed passed to the same object.
Consider code which is identical in its behaviour, but using a fluent style:
ButtonWidget widget = new ButtonWidget()
.dimensions(100, 60)
.backgroundColour(Colour.BLUE)
.text("Click Me!");
Maybe that took fewer keystrokes to write, and saved a couple of seconds of typing, but the cost is it not being immediately obvious to the reader whether there's a single ButtonWidget
or whether some or all of those methods returned different objects.
If there is only one object, then what has the fluent style gained over traditional OO message-passing style? And why not just go back to that traditional style which everybody already knows and recognises?
A key benefit of fluent interfaces is the way in which it promotes immutability; if you're not going to take advantage of that, then why even bother in the first place?