3
votes

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?

2
randomthoughtsonjavaprogramming.blogspot.be/2013/10/… . Also check the references for the Martin Fowler articles. - Nico Van Belle

2 Answers

2
votes

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.

0
votes

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();