I am mostly interested in Java, but I think it\'s a general question. Recently I\'ve been working with Arquillian framework (ShrinkWrap
) that uses a lot of meth
Method chaining is a way to implement fluent interfaces, regardless of the programming language. Main benefit of it (readable code) tells you exactly when to use it. If there is no particular need for the readable code, better avoid using it, unless the API is naturally designed to return the context/object as a result of the method calls.
Fluent interface must be considered against command-query API. To understand it better, let me write a bullet-list definition of the command-query API below. In simple words, this is just a standard object-oriented coding approach:
Command
. Command does not return a value.Query
. Query does not modify the data.Following the command-query API will give you the benefits like:
But the command-query API exists for some reason, and it indeed, reads better. Then how do we have the benefits of both fluent interface and command-query API?
Answer: fluent interface must be implemented on top of the command-query API (as opposed to replacing the command-query API by the fluent interface). Think of a fluent interface as a facade over the command-query API. And after all, it's called fluent "interface" - a readable or convenience interface over the standard (command-query) API.
Usually, after the command-query API is ready (written, probably unit-tested, polished to easily debug), you can write a fluent interface software layer on top of it. In other words, fluent interface accomplishes its functions by utilizing the command-query API. Then, use the fluent interface (with method chaining) wherever you want a convenience and readability. However, once you want to understand what's actually happening (e.g. when debugging an exception), you can always dig into the command-query API - good old object-oriented code.