'Difference between method chaining and fluent interface
I wanted to know the exact difference between method chaining and fluent interface. As I understand it, method chaining is just running the methods of previous method return objects while avoiding temporary variables. An example of this could be
Integer.parseInt(str).intValue()
With respect to fluent interface, each method of the object is chained by a point, without having to be related to the previous method The two techniques make modifiers methods return to host objects, so that multiple modifiers can be invoked in a single expression like this:
new Car().StartsEngine().OpenWindow()
is this correct?
Solution 1:[1]
I don't think there's a major difference; or rather, the two concepts are at different layers. Method chaining is the simple thing where you call a method directly on the return value of a different method.
A fluent interface is a style of designing an API to do a multiple-step, complex operation so that it reads close to prose. A fluent interface will be meant to be used through method chaining. It can use the same mutable object for every call, or it can return a new immutable object every time, depending on what the interface author thinks is a good idea.
Solution 2:[2]
Fluent interfaces can be achieved through method chaining, but all method chaining are Fluent interfaces. In Fluent interfaces, method chaining always returns the same interface which is used by all chaining methods. For example:
public interface Car
{
Car StartEngine();
Car OpenWindows();
Car CloseWindows();
Car startAC();
}
Now Fluent interfaces is implemented with chaining as follows:
Car hondaCity = new HondaCity();
hondaCity.startEngine().openWindows().closeWindows().startAC();
Now simple method Chaining example:
Car hondaCity = new HondaCity();
hondaCity.getEngine(). //Get Engine Object
getFilter(). // get Filter Object
cleanFilter();
Solution 3:[3]
In my opinion, if we ignore the type system, fluent interface is exactly the same as method chaining.
However, fluent interface is more about utilizing the type system on the return type to constrain the next potential chaining method candidates.
In a cleverly designed DSL with fluent interface, each method invocation would modify the return type so as to allow a small set of logically appropriate methods to be chained next (a bit like state machine). Hence the control flow is validated in compile time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | millimoose |
Solution 2 | Sandeep Kokate |
Solution 3 |